I'm wondering if it's possible to determine if a given address is on the stack or in the heap. I'd like this because a reference counting system we use has a flaw that if a smart pointer is somehow pointed at an object on the stack, bad things can happen. If I had this functionality, I could use it to detect this error condition early and throw so that the developer doing this would be forced to deal with this immediately.
No, this is not possible or supported. (Well, it may be possible if you want to rely on undefined or implementation defined behavior... I strongly advise you to not do that.) The typical explanation of stack and heap taught in Computer Science courses has very little in common with how real systems (which use Virtual Memory) operate.
Generally speaking it is not worth it. (If it was, std::auto_ptr
, std::unique_ptr
, or boost::shared_ptr
, or boost::scoped_ptr
would do it) C and C++ users are generally used to working with APIs which allow undefined behavior if the user does something stupid. Particularly when storage locations (stack versus free store) are concerned.
Any solution would have to be platform specific. In Windows, you can use HeapWalk to enumerate all chunks of memory in the heap. In Unix, you can try to use pthread_attr_getstack().
The direct answer to your question is that GCC supports inline assembly language, which will let you compare pointers to the stack pointer.
But you might prefer forcing your objects to be heap-allocated so you won't have this problem in the first place.