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:
- Is this the correct way to free memory for a 2D array in C? 
- 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 ? 
- 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? 
- Is this undefined behaviour expected? 
 
     
    