How to make debugging C++ errors easier.

heapwolf
3 min readSep 14, 2015

--

Out of the box, with clang, when you compile a program you get comprehensive stack traces for compile-time errors with lots of output options.

Compile-time debugging…

Here’s a simple vanilla example (short for the purpose of this demonstration)…

Not too bad. File, line number, column, error explanation. More complex errors will show more details as the stack unwinds. That’s all very straight forward, let’s move on…

Run-time debugging…

But what about run-time errors? What do they look like out of the box? Well here’s one…

Ugh, that’s not very useful. Something went wrong and it could have happened anywhere in the program! Well, it only takes a little code to make this situation a bit better. Here’s a rough concept hack that gets us a bit of a stack trace for uncaught runtime exceptions.

Let’s add that to our “very bad program”.

Now, when we run the new code, it crashes with some more useful output!

From this output, we know approximately where in the program things went wrong. Basically, `main()` called `foo()`, then `foo()` called an anonymous lambda that called another anonymous lambda from the namespace `sample`.

That’s better… ish. It should be fine for silly mistakes during development. But with this method, it’s actually quite difficult to get many of the relevant details we would need to debug a production application. So for the case where you really need to dive in and get serious, there is the amazing lldb!

We can use lldb to leverage core dumps. Core dumps are significantly more powerful than stack traces because you can know everything about the state of a program when it crashed. We can enable core dumps with `ulimit -c unlimited`. Now let’s say on OSX, when a program calls `abort()`, a core file will get dumped to `/cores/core.51101/` (that number in the file name is the pid). We can then load that with lldb using the command `lldb -c /cores/core.51101`. lldb will open as a command line interface and there are a lot of really nice, quick commands you use. But for fun, let’s just type `gui`.

Wow! A massive improvement to our debugging experience. We can see the source, step through it, investigate the thread specific stack frames, see where things went wrong and the variables involved along the way. We can even attach the debugger to a running process.

In summary, lldb is an incredibly powerful tool. It runs on Linux, OSX and Windows support is in active development! Until next time, happy debugging!

--

--