I am new to the C language, and I am trying to allocate the memory dynamically with Malloc, then free the memory with "free".
I have tried searching on google but it does not make sense so far since I just started learning it.
#include <stdio.h>
#include <stdlib.h>
int main (){
printf("Enter your name:");
//Here I allocate enough memory for the "sir" array.
//allocate memory
char *sir = (char*) malloc (100 * sizeof(char));
//scan string. I am scanning a name e.g.: John Smith
scanf("%[^\n]", sir);
//size of sir
int size = strlen(sir);
printf("String size with strlen = %d\n", size);
//printing the string
for(int i = 0; i < size; i++){
printf(" %d = [%c] ", i ,sir[i]);
}
//Printing J o h n _ S m i t h
//Here I release the memory allocated
//release memory
free(sir);
//print the string after releasing memory
printf("\n\n");
for(int i = 0; i < size; i++){
printf(" %d = [%c] ", i ,sir[i]);
}
//Printing _ _ _ _ _ S m i t h
//After the above loop, I still have some input as well as some memory which I can access.
// I do not understand why free does not release whole memory.
return 0;
}
I am expecting that after the free(sir) line, the memory I am trying to access is null/unaccessible.
I understand this wrong?
Thank you in advance.