How to know if a pointer points to the heap or the stack?

Viewed 12621

Example:

bool isHeapPtr(void* ptr)
{
     //...
}

int iStack = 35;
int *ptrStack = &iStack;
bool isHeapPointer1 = isHeapPtr(ptrStack); // Should be false
bool isHeapPointer2 = isHeapPtr(new int(5)); // Should be true
/* I know... it is a memory leak */

Why, I want to know this:

If I have in a class a member-pointer and I don't know if the pointing object is new-allocated. Then I should use such a utility to know if I have to delete the pointer.

But:
My design isn't made yet. So, I will program it that way I always have to delete it. I'm going to avoid rubbish programming

14 Answers
Related