The ability to enumerate stack frames at runtime is one of the interesting features introduced in C++23. This is made possible through the <stacktrace> header.
The interface is quite simple. Here is a piece of code showing how to use the library.
There are 4 functions and here is the call chain:
The “dumpStackTrace()” function gets the currently active stack frame sequence, enumerates over each frame and dumps the function name, source file and line number.
Here is the program output:
The output shows 10 stack frames, starting with “dumpStackTrace()”, going up to “main()” and even beyond. Keep in mind that this information is implementation dependent.
Let us now set a breakpoint in the code and look at the stack structure at runtime within Visual Studio IDE. Here is the code with breakpoint:
When you debug this program, control stops at the breakpoint and you can see the active stack frames:
You can see that this more or less matches our earlier output.
If needed, we can get the number of active stack frames in the current environment and access any of these frames using the indexing “[]” operator. This is shown in the revised “dumpStackTrace()” function:
Here, I am only accessing the topmost 4 frames (up to “main()”). This is the corresponding output:
The <stacktrace> library, while permitting access to the individual stack frames with basic details, doesn’t allow us to access the contained local variables. Maybe that will be part of a future extension.
Since this feature is part of C++23, you have to enable the corresponding setting in Visual Studio:
I used Visual Studio 2022 (64 bit Edition), version 17.6.2 for this experiment.
Have a great week!
Recent Comments