anandamu16
anandamu16

Reputation: 123

How to free 2D array memory in C

I am trying to allocate memory for 2D Array. But when I am trying to free up the memory it throws the segmentation fault. Kindly help me to know what I am doing wrong?

  int **arr1 = (int **) malloc (rows * columns * sizeof (int));

  //Array Access:
  for (i = 0; i < rows; i++)
    for (j = 0; j < columns; j++)
      *(arr1 + i * columns + j) = ++count;

  for (i = 0; i < rows; i++)
    for (j = 0; j < columns; j++)
      printf ("%d", *(arr1 + i * columns + j));

  for (i = 0; i < rows*columns; i++)
    free (arr1[i]);

Upvotes: 1

Views: 1684

Answers (3)

safakeskin
safakeskin

Reputation: 718

You can loop over each row and at each iteration, you can allocate space at creation phase and free at clearing phase it by yourself. Your code have several problems, I think that may be a better approach to write in a form like:

int **array = (int**) malloc( row * sizeof(int*)), i = 0, j;

for( ; i < row; i++){
    *(array + i)  = (int*) malloc(col * sizeof(int));
    for( j = 0; j < col; j++){
        *(*(array + i) + j) = i * row + j;
    }
}

This will create the 2d array with the values in increasing order.

While freeing:

for(i = 0 ; i < row; i++){
    free(*(array + i));
}
free(array);

Upvotes: 1

Schwern
Schwern

Reputation: 164819

A simple rule of thumb is for every malloc there should be a free. You've allocated a block of memory that arr1 points to, so you should deallocate that one block of memory.

free(arr1);

You can't free a block of memory piecemeal. If you want to do that, you need to allocate each row individually, but using a single hunk of memory as a 2D array is also fine. Allocating each row is better if the size of each row is unknown. One big allocation is better if the row size is fixed.


In addition, arr1 should be a single pointer, not a double pointer. Compiler warnings should have warned you about this.

int *arr1 = malloc (rows * columns * sizeof(int));

A double pointer is a pointer to a pointer. It's not necessary to make a double pointer to pretend a pointer is a 2D matrix.

Upvotes: 3

Paul
Paul

Reputation: 380

It looks like you are trying to allocate an array of pointers to arrays. Your code segfaults because you free non-allocated memory. The proper way to allocate a "2D array" is more like this:

int **arr1 = malloc (rows * sizeof (int*));

for (int r = 0; r < rows; r++)
  arr1[r] = malloc(columns * sizeof(int));

...

for (int r = 0; r < rows; r++)
  free(arr1[r]);

free(arr1);

Upvotes: 5

Related Questions