简体   繁体   中英

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?

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

Just the opposite of allocation:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM