Hello I am leaning c in school, and having a little confusion learning about dynamic memory allocation.
here, I allocated 10*4bytes of memory to a pointer 'a'. then assigned 10 values.
what I am confused on is that I do not know what free() does.
I thought it releases the allocated memory of the pointer, therefore it will also releases the values that are assigned.
But after free(), I printed out the values of a, and they are still there.
so what is exactly "releasing the memory" or de-allocateing the memory?
I guess it is nothing with the values that already assigned. Could you explain what I am confusing ?
#include <stdio.h>
#include <stdlib.h>
int* array_of_squares(int n)
{ 
  int* ret = (int*) malloc(n * sizeof(int));
  
  if (ret == NULL)
  
    return NULL;
  for (int i = 0; i < n; i++)
  
    ret[i] = i*i;
    
  return ret;
}
int main() { 
  int size = 10;
  int* a = array_of_squares(size);
  
  if (a == NULL)
  {
    printf("malloc failed");
    return -1;
  }    
  for (int i = 0; i < size; i++)
 
    printf("a[%d] = %d\n", i, a[i] );
  printf("\n---------------------------\n");
  
  free(a);
  //after free, the memory of pointer a is released, the values are still there. what is the point of using free?
for (int i = 0; i < size; i++)
  //until i hits 10 , so 10 times for loop
    printf("a[%d] = %d\n", i, a[i] );
  return 0;
}
output is
a[0] = 0
a[1] = 1
a[2] = 4
a[3] = 9
a[4] = 16
a[5] = 25
a[6] = 36
a[7] = 49
a[8] = 64
a[9] = 81
---------------------------
a[0] = 0
a[1] = 1
a[2] = 4
a[3] = 9
a[4] = 16
a[5] = 25
a[6] = 36
a[7] = 49
a[8] = 64
a[9] = 81
