当试图通过堆管理器分配的内存,比要求其分配更多的会发生什么? [英] what happens when tried to free memory allocated by heap manager, which allocates more than asked for?

查看:131
本文介绍了当试图通过堆管理器分配的内存,比要求其分配更多的会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题是问我的采访时说。

This question was asked to me in an interview.

假设的char * p =的malloc(n)的分配N多,说的内存N字节分配和免费的(P)是用来释放分配至P的内存。

Suppose char *p=malloc(n) assigns more than n,say N bytes of memory are allocated and free(p) is used to free the memory allocated to p.

可以堆管理器中执行这些错误的配置呢?
现在会发生什么,将n个字节被释放或N个字节被释放?

can heap manager perform such faulty allocation ? what happens now, will n bytes are freed or N bytes are freed?

有什么方法找到多少内存被释放?

is there any method to find how much memory is freed?

修改

有没有发现多少内存被释放的方法?

聊胜于无,

mallinfo()可以流下指出的弗雷德·拉尔森

mallinfo() can shed some light as pointed by "Fred Larson"

推荐答案

是的,这是几乎每一次会发生什么你一个的malloc()。在的malloc 块头包含块的大小,当免费()被调用时,它返回信息这一数额回堆。这不是故障,它的预期运行。

Yes, that's what happens almost every time do you a malloc(). The malloc block header contains information about the the size of the block, and when free() is called, it returns that amount back to the heap. It's not faulty, it's expected operation.

一个简单的实现可能,例如,卖场只是在空间中的块的大小立即preceding返回的指针。然后,免费()会是这个样子:

A simple implementation might, for instance, store just the size of the block in the space immediately preceding the returned pointer. Then, free() would look something like this:

void free(void *ptr)
{
    size_t *size = (size_t *)ptr - 1;

    return_to_heap(ptr, *size);
}

其中, return_to_heap()这里用来指,做一个函数指定的存储块返回到堆中以供将来使用的实际工作。

Where return_to_heap() is used here to mean a function that does the actual work of returning the specified block of memory to the heap for future use.

这篇关于当试图通过堆管理器分配的内存,比要求其分配更多的会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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