是否可以找到分配给指针的内存,而无需搜索 malloc 语句 [英] Is it possible to find the Memory Allocated to the Pointer, without searching for the malloc statement

查看:7
本文介绍了是否可以找到分配给指针的内存,而无需搜索 malloc 语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我已经为函数 foo 中的某个指针分配了内存:

Suppose I have allocated memory to some pointer in a function foo:

void foo()
{    
    // ...  
    int *ptr = malloc(20*sizeof(int));  

    bar (ptr);
}  

foo(),我将这个指针传递给 bar(),让我们说从 bar() 到另一个函数.

From foo(), I pass this pointer to bar() and let's say from bar() to another function.

现在,在某个时间点,我想检查:为指针分配了多少内存.

Now, at some point of time, I want to check: How much memory was allocated to the pointer.

有没有可能的方法,不用搜索语句:

Is there any possible way, without searching for the statement:

int *ptr = malloc(20*sizeof(int)); 

使用 GDB 计算分配给指针的内存量?

to figure out how much memory is allocated to the pointer, using GDB?

谢谢.

推荐答案

答案是:它依赖.

许多系统提供 msize() [1]、malloc_usable_size() [2] 或类似功能.如果你在这样的系统上,(gdb) print malloc_usable_size(ptr) 就是你所需要的.

Many systems provide msize() [1], malloc_usable_size() [2], or similar function. If you are on such a system, (gdb) print malloc_usable_size(ptr) is all you need.

[1] http://msdn.microsoft.com/en-us/library/z2s077bc(v=vs.80).aspx
[2] http://www.slac.stanford.edu/comp/unix/package/rtems/doc/html/libc/libc.info.malloc.html

这篇关于是否可以找到分配给指针的内存,而无需搜索 malloc 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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