Can I check if an object (passed by pointer or reference) is dynamically allocated?
Example:
T t;
T* pt = new T();
is_tmp(&t); // false
is_tmp(pt); // true
I perfectly realise this smells like bad design, and as a matter of fact it is, but I am trying to extend code I cannot (or should not) modify (of course I blame code that isn't mine ;) ). It calls a method (which I can override) that will delete
the passed object among other things that are only applicable to dynamically allocated objects. Now, I want to check whether I have something that is okay to be delete
d or if it is a temporary.
I will never pass a global (or static) variable, so I leave this undefined, here.
Not portably. Under Solaris or Linux on a PC (at least 32 bit Linux), the stack is at the very top of available memory, so you can compare the address passed in to the address of a local variable: if the address passed in is higher than that of the local variable, the object it points to is either a local variable or a temporary, or a part of a local variable or temporary. This technique, however, invokes undefined behavior right and left—it just happens to work on the two platforms I mention (and will probably work on all platforms where the stack is at the top of available memory and grows down).
FWIW: you can also check for statics on these machines. All statics are
at the bottom of memory, and the linker inserts a symbol end
at the
end of them. So declare an external data (of any type) with this name,
and compare the address with it.
With regards to possibly deleting the object, however... just knowing that the object is not on the heap (nor is a static) is not enough. The object might be a member of a larger dynamically allocated object.
In general, as DeadMG said, there's no way you can tell from a pointer where it comes from. However, as a debugging or porting or analyzing measure, you could add a member operator new
to your class which tracks dynamic allocations (provided nobody uses the explicit global ::new
-- that includes containers, I'm afraid). You could then build up a set<T*>
of dynamically allocated memory and search in there.
That's not at all suitable for any sort of serious application, but perhaps this can help you track where things are coming from. You can even add debug messages with line numbers to your operator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With