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?
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()
.
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:
-
g_ptr_array_free()
for freeing arrays of pointers, -
g_strfreev()
for freeing arrays of strings.
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.