Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C freeing 2D array if malloc fail

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.

like image 516
John Doe Avatar asked Jun 18 '26 02:06

John Doe


1 Answers

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.

like image 116
unwind Avatar answered Jun 19 '26 16:06

unwind