当使用free()释放内存时,为什么指针所指向的内容没有改变? [英] Why are the contents pointed to by a pointer not changed when memory is deallocated using free()?

查看:214
本文介绍了当使用free()释放内存时,为什么指针所指向的内容没有改变?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于动态内存分配,我是新手.当我们使用void free(void *ptr)释放内存时,将释放内存,但不会删除指针的内容.这是为什么?最新的C编译器有什么区别吗?

I am a newbie when it comes to dynamic memory allocation. When we free the memory using void free(void *ptr) the memory is deallocated but the contents of the pointer are not deleted. Why is that? Is there any difference in more recent C compilers?

推荐答案

计算机不会像这样删除"内存,它们只是停止使用对该内存单元的所有引用,而忘记了任何有价值的东西都存储在那里.例如:

Computers don't "delete" memory as such, they just stop using all references to that memory cell and forget that anything of value is stored there. For example:

int* func (void)
{
  int x = 5;
  return &x;
}

printf("%d", *func()); // undefined behavior

功能完成后,程序将停止保留x的存储位置,程序的任何其他部分(或其他程序)都可以自由使用它.因此,上面的代码可能显示5,或者可能显示垃圾,甚至可能使程序崩溃:引用不再有效的存储单元的内容是未定义的行为.

Once the function has finished, the program stops reserving the memory location where x is stored, any other part of the program (or perhaps another program) is free to use it. So the above code could print 5, or it could print garbage, or it could even crash the program: referencing the contents of a memory cell that has ceased to be valid is undefined behavior.

动态内存也不例外,并且以相同的方式工作.调用free()后,任何人都可以使用该部分内存的内容.

Dynamic memory is no exception to this and works in the same manner. Once you have called free(), the contents of that part of the memory can be used by anyone.

此外,请参见此问题

这篇关于当使用free()释放内存时,为什么指针所指向的内容没有改变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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