I have this code snippet to understand the memory management function void free(void*)
in C. What I know about free
function is that it will deallocate the memory that is managed by a pointer. I want to see what will happen after a block of memory is set free and whether the pointer associated is still accessible to that block of memory.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STR_SIZE 20
int main(int argc, char *argv[])
{
char originalChar [] = "123456789";
char *myChar = (char*) malloc(sizeof(char) * STR_SIZE);
if (!myChar) {
printf("allocation failed!");
exit(1);
}
char *isOk = strncpy(myChar, originalChar, STR_SIZE*sizeof(char));
if(!isOk) exit(1);
char *myCharCopy = myChar;
printf("oC = %d, mCC = %d; mC = %d\n", originalChar, myCharCopy, myChar);
printf("The strings = %s\n", myChar);
printf("The strings = %s\n", myCharCopy);
free(myChar);
printf("----- free happened here -----\n");
// myChar = NULL;
printf("oC = %d, mCC = %d; mC = %d\n", originalChar, myCharCopy, myChar);
printf("The strings = %s\n", myChar);
printf("The strings = %s\n", myCharCopy);
return 0;
}
Then, I got those results from its output.
oC = 1482066590, mCC = 826278544; mC = 826278544
The strings = 123456789
The strings = 123456789
----- free happened here -----
oC = 1482066590, mCC = 826278544; mC = 826278544
The strings = 123456789
The strings = 123456789
This result makes very little sense to me. Because free
function is supposed to set free the block of memory but it is NOT from the result. What on earth happened here? Besides, it seems the pointer associated with the memory on heap is still accessible to that freed memory. Why this will happen since it is freed?