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

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

问题描述

我读的地方,这是灾难性的使用免费来摆脱不通过调用创建的对象的的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.

让我们看看会发生什么,当你尝试免费()自动变量。堆管理器将演绎如何利用内存块的所有权。要做到这一点,将不得不使用一些独立的结构,它列出了所有分配的块,而且是很慢的一个很少使用或希望必要的数据靠近块的开始。

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;
 }

然后免费()将试图通过补偿传递指针,但访问这些数据如果指针是一个自动变量的所有数据将设在那里它希望找到服务数据。因此,不确定的行为。很多时候,业务数据是由修改免费()的堆管理器把块的所有权 - 所以,如果传递的指针是一个自动变量一些无关的内存将被修改,从阅读。

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()家庭功能通过返回的地址。

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

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

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