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

Check if a pointer points to allocated memory on the heap(检查一个指针是否指向堆上分配的内存)
本文介绍了检查一个指针是否指向堆上分配的内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我想知道一个指针是否指向一块用malloc/new分配的内存.我意识到任意地址的答案是不,你不能",但我确实认为可以覆盖 malloc/free 并跟踪分配的内存范围.

您知道提供此特定工具的内存管理库吗?
您了解生产代码吗?

Valgrind 很棒,但仪器太多(慢),正如 Will 所说,我们不想像这样使用 Valgrind(使软崩溃就足够了).
Mudflap 是一个非常好的解决方案,但专用于 GCC,遗憾的是,检查并没有简单地返回一个布尔值(见下面我的回答).
请注意,检查内存写入是否合法是一个安全问题.所以追求性能是有动力的.

解决方案

没有标准的方法可以做到这一点,但各种 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

这篇关于检查一个指针是否指向堆上分配的内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Could I ever want to access the address zero?(我可以想访问地址零吗?)
C++ Access derived class member from base class pointer(C++ 从基类指针访问派生类成员)
Weird Behaviour with const_cast(const_cast 的奇怪行为)
Are pointer variables just integers with some operators or are they quot;symbolicquot;?(指针变量只是带有某些运算符的整数还是“符号?)
Modifying a char *const string(修改 char *const 字符串)
Modifying a const int in C++(修改 C++ 中的 const int)