Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect dynamically allocated object?

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

Context

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 deleted or if it is a temporary.

I will never pass a global (or static) variable, so I leave this undefined, here.

like image 505
bitmask Avatar asked Feb 22 '23 23:02

bitmask


2 Answers

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.

like image 95
James Kanze Avatar answered Mar 08 '23 15:03

James Kanze


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.

like image 30
Kerrek SB Avatar answered Mar 08 '23 17:03

Kerrek SB