I am wondering what is the best way to clean up allocated memory during creation of dynamic array in C and C++. Let's forget for a moment about boost, standard library and all the awesome containers / smart pointers. Let's think about this the hard way.
// 2D in C, malloc
int** a = (int**)malloc(rows * sizeof(int*));
for (int i = 0; i != rows; ++i)
a[i] = (int*)malloc(columns * sizeof(int));
// 2D in C, calloc
int** b = (int**)calloc(sizeof(int*) * rows, sizeof(int*));
for (int i = 0; i != rows; ++i)
b[i] = (int*)calloc(sizeof(int) * columns, sizeof(int));
// 2D in C++, new
int** c = new int*[rows];
for (int i = 0; i != rows; ++i)
c[i] = new int[columns];
for (int i = 0; i != rows; ++i)
{
free(a[i]);
free(b[i]);
delete[] c[i];
}
free(a);
free(b);
delete[] c;
In C both, malloc and calloc, can return null pointer. In C++ std::bad_alloc can be thrown. What is the safe way for creating multidimensional arrays in C and C++ for such scenarios? When writing in C should we keep comparing returned pointers with NULL and if true then break the loop and cleanup everything? How? In C++ should we use try-catch block? Can case for C++ be templated with typename T?
Thanks in advance.
Aucun commentaire:
Enregistrer un commentaire