Why freed struct in C still has data?

后端 未结 7 1182
梦毁少年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:09

    sizeof is a compile-time operation, so memory allocation won't change how it works.

    free does not erase memory, it just marks the block as unused. Even if you allocate a few hundred megabytes of memory, your pointer may still not be overwritten (modern computers have lots of RAM). However, after you free memory, you can no longer depend on its value.

    See if your development environment has a memory allocation debugging setting -- some have settings to overwrite blocks with something like 0xDEADBEEF when you free them.

    Also, you may wish to adopt the habit of setting your pointer to NULL immediately after calling free (to help encourage your program to crash early and loudly).

提交回复
热议问题