lina
lina

Reputation: 1707

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?

Upvotes: 33

Views: 89666

Answers (6)

James Bedford
James Bedford

Reputation: 28962

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

Upvotes: 26

Asher Abecassis
Asher Abecassis

Reputation: 87

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

Upvotes: 1

7vujy0f0hy
7vujy0f0hy

Reputation: 9109

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.

Upvotes: 8

Srikanth
Srikanth

Reputation: 11994

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.

Upvotes: 2

Donotalo
Donotalo

Reputation: 13025

Just the opposite of allocation:

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

Upvotes: 29

Robᵩ
Robᵩ

Reputation: 168626

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().

Upvotes: 12

Related Questions