How to Free 2D Array in C?

I have the following code:

int **ptr = (int **)malloc(sizeof(int*)*N); 
for(int i=0;i<N;i++) 
     ptr[i]=(int*)malloc(sizeof(int)*N));

How can I free ptr using free? Should I loop over ptr and free ptr[i] or should I just do

free(ptr) 

and ptr will be freed?

1

6 Answers

Just the opposite of allocation:

for(int i = 0; i < N; i++)
    free(ptr[i]);
free(ptr);
4

You will have to loop over ptr[i], freeing each int* that you traverse, as you first suggest. For example:

for (int i = 0; i < N; i++)
{
    int* currentIntPtr = ptr[i];
    free(currentIntPtr);
}
7

Yes, you must loop over ptr and free each ptr[i]. To avoid memory leaks, the general rule is this: for each malloc(), there must be exactly one corresponding free().

Simple

while (N) free(ptr[--N]);
free(ptr);
Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.