Search code examples
cmultidimensional-arraymemory-leakscallocnull-pointer

Should I check for NULL pointer after malloc and calloc of 2D array in C?


OK, I acknowledge that I should check for NULL pointer when mallocing, but what about calloc? Are there any memory leaks possible?

int **initializeMatrix(int *rows, int *cols) {
    int **matrix = malloc((*rows) * sizeof(int*));
    checkNullPointer(matrix);
    for(int i = 0; i < *rows; i++) {
        matrix[i] = calloc(*cols, sizeof(int));
    }

    return matrix;
}

void checkNullPointer(int **ptr) {
    if (ptr == NULL)
        printErrorMessage(memoryErrorMessage, 101);
}

Solution

  • You do indeed need to check the return value of calloc (it will be NULL if memory could not be allocated), but note that calling free on a NULL pointer is a no-op, so there is no immediate memory leak per se.

    Of course, when cleaning up after encountering a NULL return, you'll need to call free on all non-NULL pointers emanating from successful calloc calls. Personally I'd call calloc on the row allocation too to make that process simpler.