为什么在 C 中释放的结构仍然有数据? [英] Why freed struct in C still has data?

查看:25
本文介绍了为什么在 C 中释放的结构仍然有数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我运行此代码时:

#include <stdio.h>

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

int
main (int argc, char **argv)
{
    Food  *food;

food = (Food*) malloc (sizeof (Food));
snprintf (food->name, 128, "%s", "Corn");

free (food);

printf ("%d
", sizeof *food);
printf ("%s
", food->name);
}

我还是明白了

128
Corn

虽然我已经释放了食物.为什么是这样?内存真的释放了吗?

although I have freed food. Why is this? Is memory really freed?

推荐答案

当您释放食物"时,您就表示您已经完成了它.但是,指针 food 仍然指向相同的地址,并且该数据仍然存在(在不需要时必须将释放的每一位内存清零会造成太多开销)

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)

基本上是因为它是一个如此有效的小例子.如果在 free 和 print 语句之间有任何其他 malloc 调用,您可能不会看到这一点,并且很可能会以某种可怕的方式崩溃.你不应该依赖这种行为.

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.

这篇关于为什么在 C 中释放的结构仍然有数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆