如何检测,其中的内存块被分配? [英] How to detect where a block of memory was allocated?

查看:126
本文介绍了如何检测,其中的内存块被分配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

的内存块,可静态分配,在堆栈或堆中。我想知道的路要走,如果一个指针指向堆检测。我与Windows和Linux工作,它是没有问题的为每个OS不同的解决方案。我用GCC和MinGW。

如果我能知道在哪里堆开始,在哪里结束,我认为这个问题是可以解决的。我认为,我可以检测底部和堆栈,以了解是否该块是在堆栈的顶部,但是,如果有多个线程,则有多个栈。连我自己都知道哪里是静态存储器,我想我会与共享库的静态存储器块的问题。

我想我将有一个问题,如果指针不指向块的开头:

 键入* X =及(指针[3]);


解决方案

您不能。

您可以尝试在您程序的开头在堆上分配内存,并比较地址要释放的指针,但在许多情况下,它会不准确。什么,你可能会发现其内存管理的一些研究后,在一个平台上使用,可能不会对下一个相关。

这是另一种方法是内存管理模块添加到您的程序,这将包裹的malloc 免费等等功能,并跟踪所有分配的内存并调用免费仅当指针出现在他的名单。虽然这看起来像一个大量的工作,以避免内存泄漏,我发现它非常方便很多次了。

修改

正如评论所说,决定最好的办法很简单 - 释放它在一个地方,你知道,如果它是位于堆与否。我不能告诉你,这是你的情况多么容易,但通常它不应该太难,许多程序/编程人员之前做了,而且我怀疑有人真的试图以检查内存在分配的。

A block of memory can be allocated statically, in the stack or in the heap. I want to know a way to detect if a pointer points to the heap. I work with Windows and Linux and it is not a problem a different solution for each OS. I use GCC and Mingw.

If I could know where the heap begins and where it ends, I think the problem can be solved. I think that I can detect the bottom and the top of the stack in order to know if the block is in the stack, but if there are multiple threads, then there are multiple stacks. Even I could to know where is the static memory, I think I will have problems with static memory blocks of shared libraries.

I think I will have a problem if the pointer does not point to the beginning of the block:

type* x =  &(pointer[3]);

解决方案

You can't.

You may try to allocate a memory on the heap at the beginning of you program, and compare the address to the pointer you want to free, but it will not be accurate in many of the cases. And what you might find and use on one platform after some research of its memory management, might not be relevant on the next.

An alternate way is to add a memory management module to your program, which will wrap the malloc, free etc. functions and will keep track of all allocated memory and will call free only if the pointer appears in his list. While this might seem like a lot of work to avoid memory leaks, I've found it very convenient many times.

EDIT
As mentioned in comments, the best way to decide is simple - free it in a place where you know if it's was located on the heap or not. I cannot tell you how easy it is in your case, but usually it shouldn't be too hard, many programs / programers did it before, and I doubt someone actually tried to check where the memory was allocated at.

这篇关于如何检测,其中的内存块被分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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