VoidWalker VoidWalker - 8 months ago 59
C++ Question

Object allocation on stack or heap

I'm trying to make a mechanism that could tell where the object of the class is allocated.
Thought about making a flag in the class, but it's not possible to set a value because object's lifetime is not started during the call of "new" operator.
Is it possible in C++ to tell if an object is on stack or heap (runtime)?


There is no portable way to do this, but if we assume you have a limited amount of system types where you are going to do this on, you could try the following:

Take the address of some local variable in main (or other "low in the callstack"). Store this in a global variable, lets call char *stackbase;

Then take the address of a local variable in your function that you are checking in, let's call it char *stacktop;

Now, if we have a char *obj = reinterpret_cast<char *>(object_in_test);, then:

if (obj > stacktop && obj < stackbase) on_stack = true;
else on_stack = false; 

Note that there are SEVERAL flaws with this:

  1. It's technically undefined behaviour. It will work on most systems, because the whole memory space is contiguous. But there are systems where the stack and other sections of memory have separate "address spaces", which means that two pointers to different types of memory can have the same address.
  2. Threads will need to have a "per thread stackbase".
  3. The stack is assumed to "grow towards zero" (if not, you'll have to invert the > and < in the if.
  4. Global variables will be seen as not on stack.

I fully expect to have to delete this answer as it will be downvoted by language lawyers, despite the disclaimer below.