Caveat: this uses "unedfined behavior" as described below - it is known to work on MOST platforms (I have enough understanding to say that it works on ARM and x86 on Windows, Linux and Symbian OS, and should be good for most OSs that use a "flat" memory model).
If you "limit" yourself to a particular system, you can compare this with the known range of "where is the stack" (and, if necessary), where is the static data). [One could figure out where the stack is for an arbitrary thread too, but this makes the task difficult].
Given where the static data and the stack are, we can compare
char *this_addr = static_cast<char*>(this); if (this_addr >= globa_start && this_addr <= global_end) globals++; else if (this_addr >= stacK_top && this_addr >= stack_base) stacked++; else heaped++;
Please note that this will only work if you can somehow determine where the stack is located, and, of course, the undefined behavior for comparing this with anything outside the block in which it was allocated, so technically , the concept is undefined. However, it is POSSIBLE to do this in most OS / Processor architectures. [Of course, you also need to do the same, but vice versa in the destructor]. (It also gets "pleasure" if you destroy an object from another thread, except the one that created it!)
Edit: Finding a stack for a given stream is not so difficult: save [to the stream, if there are several threads], the address of the local variable in the "first function" (the one that passed into the stream calls up). Then take the address of the variable in the current thread. Everything that is between these values ββis on the thread stack, since the stack is one continuous piece of memory.
Mats petersson
source share