If i have a 2D array allocated as follows:
int** map;
map = malloc(number * sizeof(int*));
if(!(map)){
printf("out of memory!\n");
return 1;
}
for (int i = 0; i < number; i++){
map[i] = malloc(number * sizeof(int));
if (!(map[i])){
printf("Not enough memory!\n");
return 1;
}
}
If the allocation fails and we enter in the if statement should i free map and the "columns" allocated until now? If so, how should i do it?
Right now i just print the message and return 1 but i'm not sure if this is the correct approach.
Yes, you should free() otherwise you leak memory which might matter if this is in a long-running program.
One way to make it easier is to compute the total size of all the allocations, and do a single larger malloc() rather than a whole bunch of smaller ones. This is also (potentially much) faster, since heap allocations can be expensive.
That way, you only need to check once if it succeeded or failed, and there's nothing to free() in case of failure.
Something like this:
int ** map_allocate(size_t number)
{
int **base = malloc(number * sizeof (int *) + number * number * sizeof (int));
if(base != NULL)
{
int *row = (int *) (base + number);
for(size_t i = 0; i < number; ++i)
base[i] = row + i * number;
}
return base;
}
I didn't test-run this, but something along those lines.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With