我怎样才能得到一个内存块的大小分配使用malloc()? [英] How can I get the size of a memory block allocated using malloc()?

查看:161
本文介绍了我怎样才能得到一个内存块的大小分配使用malloc()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能显示的文件:

  <一href=\"http://stackoverflow.com/questions/232691/how-can-i-get-the-size-of-an-array-from-a-pointer-in-c\">How我可以得到一个数组的大小从一个指针用C?

  <一href=\"http://stackoverflow.com/questions/197839/is-there-any-way-to-determine-the-size-of-a-c-array-programmatically-and-if-n\">Is有什么方法来确定数组的一个C ++的编程大小?如果不是,为什么?

我得到一个指向分配内存的一大块了C风格的函数的。
现在,这将是非常有趣的用于调试知道如何
大分配的内存块,这个指针指向的。

I get a pointer to a chunk of allocated memory out of a C style function. Now, it would be really interesting for debugging purposes to know how big the allocated memory block that this pointer points is.

还有什么更优雅比在其边界盲目挑起运行异常?

Is there anything more elegant than provoking an exception by blindly running over its boundaries?

在此先感谢,
安德烈亚斯

Thanks in advance, Andreas

我用VC ++ 2005在Windows和Linux上的GCC 4.3

I use VC++2005 on Windows, and GCC 4.3 on Linux

_msize VC ++下的2005年
不幸的是,导致异常在调试模式下....

I have _msize under VC++2005 Unfortunately it results in an exception in debug mode....

嘛。我试图用我除了上述的方式,它的工作原理。
至少在我调试和调用后确保立即
图书馆退出我跑过来缓冲区边界。就像一个魅力。

Well. I have tried the way I described above with the exception, and it works. At least while I am debugging and ensuring that immediately after the call to the library exits I run over the buffer boundaries. Works like a charm.

这恰恰是不优雅,绝不生产code使用。

It just isn't elegant and in no way usable in production code.

推荐答案

这不是标准,但如果你的图书馆有MSIZE()函数,它会给你的大小。

It's not standard but if your library has a msize() function that will give you the size.

一个共同的解决办法是包装的malloc用自己的函数,它的大小和内存产生的区间上沿记录每个请求,在发布版本,您可以切换到真实的malloc。

A common solution is to wrap malloc with your own function that logs each request along with the size and resulting memory range, in the release build you can switch back to the 'real' malloc.

这篇关于我怎样才能得到一个内存块的大小分配使用malloc()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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