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

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

问题描述

当我运行这个code:

When I run this code:

#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\n", sizeof *food);
printf ("%s\n", food->name);
}

我仍然获得

128
Corn

虽然我已经释放的食物。为什么是这样?难道真的内存释放?

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

推荐答案

当你自由食物,你的意思是你用它做。但是,鼠标指针食尚指向同一个地址,而该数据仍然存在(这将是开销太大不得不记忆每一位的释放的零出时不需要)

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)

基本上它是因为它是这样一个小例子,这工作。如果任何其他调用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天全站免登陆