如何自由()知道多少内存释放? [英] How does free() know how much memory to deallocate?

查看:96
本文介绍了如何自由()知道多少内存释放?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/1518711/c-programming-how-does-free-know-how-much-to-free\">C编程:如何免费知道多少释放

当C编程,我经常使用的malloc()来分配内存和免费()将其释放

When programming in C, I often usemalloc() to allocate memory and free() to release it:

MyObject* objArr= (MyObject*) malloc(sizeof(MyObject)*numberOfObjects);
/** Do stuff **/
free(objArr);

如何免费()知道多少内存释放?是否的malloc()创建一个表的地方要记住指针和每个指针多少指向的内存?

How does free() know how much memory to deallocate? Does malloc() create a table somewhere to remember pointers and how much memory each pointer pointed to?

如果是这样的话,将免费()如果我重新命名指针失败?例如:

If that is the case, will free() fail if I rename the pointer? e.g.:

MyObject* objArr= (MyObject*) malloc(sizeof(MyObject)*numberOfObjects);
MyObject* newPtr= objArr;
free(newPtr); /** Does this fail? **/

如果我递增指针,然后运行会发生什么免费()?例如:

What will happen if I increment the pointer and then run free()? e.g.:

MyObject* objArr= (MyObject*) malloc(sizeof(MyObject)*numberOfObjects);
newPtr++;
free(newPtr); /** What happens now? **/

将它释放的内存增加一块就在原始数组的结束?

Will it deallocate an additional chunk of memory just off the end of the original array?

推荐答案

最常见的方式是,它返回到你的地址之前立即存储一些信息。所以,如果malloc的返回地址西班牙语 - 多米尼加共和国,在内部,malloc的将抛开记忆开始于0x0FFC,将各种信息存储,如量0xFFC之间的内存大小的地方 - 0x1003但应用程序会被告知分配开始于西班牙语 - 多米尼加共和国

The most common way is that it stores some information immediately before the address it returns to you. So if malloc returns the address 0x1004, internally, malloc will have put aside the memory started at 0x0FFC and will store various information such as the size somewhere in the memory between 0xFFC - 0x1003 but the application will be told the allocation starts at 0x1004.

这关系到自由的唯一的事情是获得完全相同的地址是什么malloc返回。

The only thing that matters to free is getting the exact same address as what malloc returned.

这篇关于如何自由()知道多少内存释放?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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