How to Free 2D Array in C?
I Have the Following Code: Int **Ptr = (Int **)Malloc(Sizeof(Int*)*N); For(Int I=0; I
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?
6 Answers
Just the opposite of allocation:
for(int i = 0; i < N; i++)
free(ptr[i]);
free(ptr);
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);
}
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().
Must Read
Simple
while (N) free(ptr[--N]);
free(ptr);