且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检查一个指针是否指向堆上分配的内存

更新时间:2023-11-28 10:15:28

没有标准的方法可以做到这一点,但各种 malloc 调试工具可能有办法做到这一点.例如,如果你使用valgrind,你可以使用VALGRIND_CHECK_MEM_IS_ADDRESSABLE来检查这个和相关的事情>

I want to know if a pointer points to a piece of memory allocated with malloc/new. I realize that the answer for an arbitrary address is "No you can't" but I do think it is possible to override malloc/free and keep track of allocated memory ranges.

Do you know a memory management library providing this specific tool?
Do you know something for production code?

Valgrind is great, but it is too much instrumentation (slow) and as Will said we don't want to use Valgrind like this (making the soft crash is good enough).
Mudflap is a very good solution, but dedicated to GCC, and sadly, a check does not simply return a boolean (see my answer below).
Note that checking that memory writes are legal is a security issue. So looking for performance is motivated.

There's no standard way to do this, but various malloc debugging tools may have a way of doing it. For example, if you use valgrind, you can use VALGRIND_CHECK_MEM_IS_ADDRESSABLE to check this and related things