为什么我不应该对不是由 malloc() 分配的变量调用 free()? [英] Why exactly should I not call free() on variables not allocated by malloc()?

查看:15
本文介绍了为什么我不应该对不是由 malloc() 分配的变量调用 free()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在某处读到使用 free 来删除不是通过调用 malloc 创建的对象是灾难性的,这是真的吗?为什么?

I read somewhere that it is disastrous to use free to get rid of an object not created by calling malloc, is this true? why?

推荐答案

这是未定义的行为 - 切勿尝试.

That's undefined behavior - never try it.

让我们看看当您尝试 free() 一个自动变量时会发生什么.堆管理器必须推断如何获得内存块的所有权.为此,它要么必须使用一些单独的结构来列出所有已分配的块并且非常慢且很少使用,要么希望必要的数据位于块的开头附近.

Let's see what happens when you try to free() an automatic variable. The heap manager will have to deduce how to take ownership of the memory block. To do so it will either have to use some separate structure that lists all allocated blocks and that is very slow an rarely used or hope that the necessary data is located near the beginning of the block.

后者经常使用,这是我应该如何工作的.当您调用 malloc() 时,堆管理器会分配一个稍大的块,在开头存储服务数据并返回一个偏移指针.喜欢:

The latter is used quite often and here's how i is supposed to work. When you call malloc() the heap manager allocates a slightly bigger block, stores service data at the beginning and returns an offset pointer. Smth like:

void* malloc( size_t size )
{
      void* block = tryAlloc( size + sizeof( size_t) );
      if( block == 0 ) {
          return 0;
      }
      // the following is for illustration, more service data is usually written
      *((size_t*)block) = size;
      return (size_t*)block + 1;
 }

然后 free() 将尝试通过偏移传递的指针来访问该数据,但如果指针指向一个自动变量,则任何数据都将位于它期望找到服务数据的位置.因此未定义的行为.很多时候,free() 会修改服务数据,以便堆管理器获得块的所有权 - 因此,如果传递的指针指向自动变量,则会修改并读取一些不相关的内存.

then free() will try to access that data by offsetting the passed pointer but if the pointer is to an automatic variable whatever data will be located where it expects to find service data. Hence undefined behavior. Many times service data is modified by free() for heap manager to take ownership of the block - so if the pointer passed is to an automatic variable some unrelated memory will be modified and read from.

实现可能会有所不同,但您不应做出任何具体假设.仅对 malloc() 系列函数返回的地址调用 free().

Implementations may vary but you should never make any specific assumptions. Only call free() on addresses returned by malloc() family functions.

这篇关于为什么我不应该对不是由 malloc() 分配的变量调用 free()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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