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);

Handsome

#define FALSE 0
#define TRUE 1
typedef int BOOL;
void freev(void **ptr, int len, BOOL free_seg) { if (len < 0) while (*ptr) {free(*ptr); *ptr++ = NULL;} else while (len) {free(ptr[len]); ptr[len--] = NULL;} if (free_seg) free(ptr);
}
freev(ptr, N, TRUE); /* if known length */
freev(ptr, -1, TRUE); /* if NULL-terminated */
freev(ptr, -1, FALSE); /* to keep array */

Patrician

GLib functions:

I find it hard to do any serious C programming without GLib. It introduces things such as dynamic strings and lays foundations for functional programming. It should really be part of the standard C run-time library. It would give C a breath of fresh air. It would make C a reasonable and competitive language again for the year 2019. But because it isn’t, it will add 1 MB to your application (either in DLL size or in executable size). Also the Windows distribution is maintained by sadists.

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

you are not checking for malloc failure to allocate. You should always check.

void freeMatrix(int **matrix ,int row)
{ for(int i=0;i<row;i++) { free(matrix[i]); } free(matrix);
}
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like