How to detect where a block of memory was allocate

2019-07-29 15:07发布

问题:

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]);

回答1:

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.