Kubekk Kubekk - 19 days ago 6
C Question

Using free(), what is happening later?

As I was reading, there is a need to use

free()
, BUT what happen next? I mean if I got something like that:

char word[] = "abc";
char *copy;
copy = (char*) malloc(sizeof(char) * (strlen(word) + 1));
strcpy(copy, word);
free(copy);
printf("%s", copy);


It is going to write me "abc". Why?

Answer

After using free(), your pointer copy still points to the same memory location. free() does not actually delete what is written there in memory but rather tells the memory management that you do not need that part of memory anymore. That is why it still outputs abc. However, your OS could have reassigned that memory to another application or some new thing you allocate in your application. If you are unlucky, you will get an segmentation fault.