检查一个指针是否指向堆上分配的内存 [英] Check if a pointer points to allocated memory on the heap

查看:22
本文介绍了检查一个指针是否指向堆上分配的内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道一个指针是否指向一块用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

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

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