Stack/Frame pointer as external variable

158 Views Asked by At

I was writing some logging logic and wanted to make some indentations. The easiest way to understand whether any function call was present or if some function has finished is to look at the current address of the stack/frame. Let's suppose that stack grows upside down. Then if the stack address in the log() call is smaller than during the previous call, we can increase the indent since some function call was present. I know there are functions like backtrace() that know how to dump it, or you can use some assembly. However, I remember reading about external variables that can be used to retrieve this information. Can someone name these variables or give a reference where I can find them (as far as I remember, it was in some computer systems book like "Computer Systems: A Programmer's Perspective "). Otherwise, what is the most convenient/fast way of getting this information?

Update: I have accidentally found the link I was referring to - Print out value of stack pointer
TLDR: There is no portable way to do what I have described...

1

There are 1 best solutions below

1
On

This method is highly nonportable and will break under various transformations, but if you're just using it for debug logging it might be suitable.

The easiest way to get something resembling the current stack frame address is just take the address of any automatic-storage (local, non-static) variable. If you want a baseline to compare it against, save the address of some local in main or similar to a global variable. If your program is or might be multi-threaded, use a thread-local variable for this if needed.