Hassen Dhia Hassen Dhia - 11 months ago 36
C Question

Are these extra lines of code needed to be bug free for array allocation in c/c++?

For two dimensional array allocation in C/C++ , the very common code is :

const int array_size = .. ;
array = (int**) malloc(array_size);
for (int c=0;c<array_size;c++)
array[c] = (int*) malloc(other_size);

But I think we should be writing this:

const int array_size = .. ;
array = (int*) malloc(array_size);
int c;
bool free_array = false;
for (c=0;c<array_size;c++) {
array[c] = (int*) malloc(other_size);
if(array[c] == NULL){
free_array = true;
if(free_array) {
for (int c1=0;c1<c;c1++)

to make sure that if one allocation failed we will free the previously allocated memory.

Am I correct?

Note : in C++ there is an alternative safe method with smart pointers and STL containers, but lets talk about raw pointers here or about C pointers.

Answer Source

Generally speaking, if you detect that malloc fails, the only thing you can really do is exit(). At that point, you can't safely do anything regarding memory allocation or deallocation.

The only exception is if you're in an embedded environment where exiting is not an option. In that case, you probably shouldn't be using malloc in the first place.