1

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]);
Squall
  • 4,344
  • 7
  • 37
  • 46
  • 2
    I don't think you can, why would you want to do this? – MByD May 07 '11 at 23:13
  • I want to avoid memory leaks. I have a pointer in a function and the pointer will not be used again, but I do not know if it points to the heap. If it points to the heap, it can be freed. – Squall May 07 '11 at 23:37
  • 3
    Of course you know, it was your code that allocated it. There is no reason whatsoever that this knowledge suddenly becomes unavailable. Beyond severely flawed program design. Trusting an oracle to provide the missing knowledge is severely flawed too. Worse, it ports like cr*p. – Hans Passant May 08 '11 at 00:23
  • I agree this is almost certainly a bad design idea, but nonetheless there is use to knowing what memory section a pointer is in. This is easy on an embedded system since it just corresponds to section boundaries. With an OS, though, you'll need to ask the OS somehow. – djs May 08 '11 at 07:39
  • If I store a pointer in an object, when the object be deleted, I will have to delete the pointer in the destructor, but the pointer must point to the heap. – Squall May 08 '11 at 19:52

1 Answers1

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.

MByD
  • 135,866
  • 28
  • 264
  • 277