in C, how do I tell if my object is allocated in the stack or the heap, or is it not really possible in a standard way?
I believe the general rule of thumb is if it is dynamically allocated, i.e. using malloc, it goes in the heap. Otherwise it is in the stack. Before posting this I decided to do a quick google search to make sure I had that right. This Stack Overflow thread agrees with my memory and provides some additional detail: http://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap
Right... but I actually wanted to know if it was possible for a program to tell whether an object in memory is located in the stack, or in the heap i.e. how to tell if an object comes from malloc()ed memory or not.
Tomas wins. So, I'm pretty sure there is a way to do that. I think there is a system call to get the starting address and ending address of your heap. If a pointer points to an address in that range, it is in the heap. Although beyond that I can't tell you any more.
:( I'll eventually figure it out :-D nice cartoon tomas
Why do you want to know, out of curiosity?
To make sure that the pointer I'm giving free() points to something from the heap, in order to prevent undefined behavior.
I don't think you need to worry about that if you design your program properly. If the pointer isn't allocated inside the function then the function shouldn't free() the pointer. You always malloc and free pointers at the same level, if possible.
Join our real-time social learning platform and learn together with your friends!