Kubekk Kubekk - 1 year ago 78
C Question

Using free(), what is happening later?

As I was reading, there is a need to use

, 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);
printf("%s", copy);

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download