Why freed struct in C still has data?

后端 未结 7 1206
梦毁少年i
梦毁少年i 2020-12-02 02:42

When I run this code:

#include 

typedef struct _Food
{
    char          name [128];
} Food;

int
main (int argc, char **argv)
{
    Food  *f         


        
7条回答
  •  广开言路
    2020-12-02 03:08

    free tells the memory allocator that it can reuse that memory block, nothing else. It doesn't overwrite the block with zeros or anything - luckily, because that could be quite an expensive operation! What it does do is make any further dereferencing of the pointer undefined, but 'undefined' behaviour can very well mean 'do the same thing as before' - you just can't rely on it. In another compiler, another runime, or under other conditions it might throw an exception, or terminate the program, or corrupt other data, so... just DON'T.

提交回复
热议问题