Search code examples
carraysmallocfree

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.


Solution

  • You can use:

    if (!(map[i])){
        printf("Not enough memory!\n");
    
        while (--i>=0)
            free(map[i]);
    
        free(map);
        return 1;
    }