Why freed struct in C still has data?

后端 未结 7 1179
梦毁少年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条回答
  •  萌比男神i
    2020-12-02 02:58

    When you free 'food', you are saying you are done with it. However, the pointer food still points to the same address, and that data is still there (it would be too much overhead to have to zero out every bit of memory that's freed when not necessary)

    Basically it's because it's such a small example that this works. If any other malloc calls were in between the free and the print statements, there's a chance that you wouldn't be seeing this, and would most likely crash in some awful way. You shouldn't rely on this behavior.

提交回复
热议问题