C++23: “stacktrace” Library

Written by on June 6, 2023 in C++, Programming with 0 Comments

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.

Enumerating Stack Frames

Enumerating Stack Frames

There are 4 functions and here is the call chain:

The Call Chain

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:

Program Output

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:

Setting Breakpoint in Code

Setting Breakpoint in Code

When you debug this program, control stops at the breakpoint and you can see the active stack frames:

Debug Stack Trace

Debug Stack Trace

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:

Accessing Stack Frames Directly

Accessing Stack Frames Directly

Here, I am only accessing the topmost 4 frames (up to “main()”). This is the corresponding output:

Controlled Access to Stack Frames

Controlled Access to Stack Frames

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:

Enabling C++23 Language Support

Enabling C++23 Language Support

I used Visual Studio 2022 (64 bit Edition), version 17.6.2 for this experiment.

Have a great week!

Tags: ,

Subscribe

If you enjoyed this article, subscribe now to receive more just like it.

Subscribe via RSS Feed

Leave a Reply

Your email address will not be published. Required fields are marked *

Top