-1

I have this code segment:

#include<stdio.h>
#include<stdlib.h>

int main()
{
    int ** ar;
    int i;
    ar = malloc( 2 * sizeof(int*));

    for(i=0; i<2; i++)
        ar[i] = malloc ( 3 * sizeof(int) );

    ar[0][0]=1;
    ar[0][1]=2;
    ar[0][2]=5;
    ar[1][0]=3;
    ar[1][1]=4;
    ar[1][2]=6;

    for(i=0; i<2; i++)
        free(ar[i]);

    free(ar);
    printf("%d" , ar[1][2]);

    return 0;
}

I went through some threads on this topic (how to free c 2d array) but they are quite old and no one is active.

I had the following queries with respect to the code:

  1. Is this the correct way to free memory for a 2D array in C?

  2. If this is the correct way then why am I still getting the corresponding array value when I try to print ? Does this mean that memory is not getting freed properly ?

  3. What happens to the memory when it gets freed? Do all values which I have stored get erased or they just stay there in the memory which is waiting for reallocation?

  4. Is this undefined behaviour expected?

sg7
  • 6,108
  • 2
  • 32
  • 40
Varad Bhatnagar
  • 599
  • 1
  • 7
  • 19

1 Answers1

1

Yes you have two levels or layers (so to speak) of memory to free.

The inner memory allocations (I like how you do those first)

The outer memory allocation for the topmost int** pointer.

Even after you freed the memory, nothing was done with it to overwrite it (So yes it's expected). Hence why you can still print them to the console. It's a good idea to always NULL your pointers after you are done with them. Kind of the polite thing to do. I've fixed many bugs and crashes in the past because the code did not null the pointers after freeing them.

In Microsofts Visual Studio, with the Debug C runtime, it can overwrite the newly free'd values with some garbage that will immediately raise an access violation if used, or dereferenced. That's useful for flushing out bugs.

It looks like you are new to C (Student?). Welcome and have a fun time.

C.J.
  • 15,637
  • 9
  • 61
  • 77