如何找到多少内存由malloc调用实际上是用了? [英] How to find how much memory is actually used up by a malloc call?

查看:167
本文介绍了如何找到多少内存由malloc调用实际上是用了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我称之为:

char *myChar = (char *)malloc(sizeof(char));

我可能会使用的内存超过1个字节是,因为的malloc很可能利用自身的一些内存来跟踪空闲块的堆是,它可以有效地花费我通过始终对准分配一些内存沿着一定的界限。

I am likely to be using more than 1 byte of memory, because malloc is likely to be using some memory on its own to keep track of free blocks in the heap, and it may effectively cost me some memory by always aligning allocations along certain boundaries.

我的问题是,:有没有办法找出多少内存由一个特定的的malloc 调用,包括有效真的用完调整成本,并通过的malloc / 免费

My question is: Is there a way to find out how much memory is really used up by a particular malloc call, including the effective cost of alignment, and the overhead used by malloc/free?

只是要清楚,我的的要求,以找出多少内存的指针指向到的malloc 通话后。相反,我调试使用的内存很大的一个程序,我想知道的code的哪些部分被分配了多少内存。我希望能有一个顶级报告的数字非常接近匹配内存核算。理想情况下,我希望能够以编程方式做到这一点对每个 - 的malloc -call的基础上,而不是在一个检查站得到一个总结

Just to be clear, I am not asking to find out how much memory a pointer points to after a call to malloc. Rather, I am debugging a program that uses a great deal of memory, and I want to be aware of which parts of the code are allocating how much memory. I'd like to be able to have internal memory accounting that very closely matches the numbers reported by top. Ideally, I'd like to be able to do this programmatically on a per-malloc-call basis, as opposed to getting a summary at a checkpoint.

推荐答案

有没有一个便携式解决方案这一点,但是有可能是操作系统特定的解决方案,为你感兴趣的环境中。

There isn't a portable solution to this, however there may be operating-system specific solutions for the environments you're interested in.

例如,用的glibc 在Linux上,你可以使用 mallinfo()函数从<&malloc.h所GT; 返回一个结构mallinfo 。在 uordblks hblkhd 此结构的成员包含该程序包括:簿记开销使用动态分配的地址空间 - 如果你把这个差别在每次后的malloc()电话,你会知道的空间,该调用使用量。 (开销不一定每次调用恒的malloc())。

For example, with glibc on Linux, you can use the mallinfo() function from <malloc.h> which returns a struct mallinfo. The uordblks and hblkhd members of this structure contains the dynamically allocated address space used by the program including book-keeping overhead - if you take the difference of this before and after each malloc() call, you will know the amount of space used by that call. (The overhead is not necessarily constant for every call to malloc()).

使用你的例子:

char *myChar;
size_t s = sizeof(char);
struct mallinfo before, after;
int mused;

before = mallinfo();
myChar = malloc(s);
after = mallinfo();

mused = (after.uordblks - before.uordblks) + (after.hblkhd - before.hblkhd);

printf("Requested size %zu, used space %d, overhead %zu\n", s, mused, mused - s);

真的不过,开销很可能是pretty未成年人,除非你正在一个非常非常高的数量非常小的拨款,这是一个不好的想法。

Really though, the overhead is likely to be pretty minor unless you are making a very very high number of very small allocations, which is a bad idea anyway.

这篇关于如何找到多少内存由malloc调用实际上是用了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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