Dangling pointers/references, undefined behaviour, memory leaks, segmentation faults, bad access, SIGABRT, Release optimizations and other C/C++ BAUs

Welcome to the real world of C++ programming, my friend. Debugging is by far the one of the most advanced and undervalued skill in programming if it’s not the most. If you’re not familiar with all these terms in the title you’re innocent person and didn’t smell a cannon powder yet. Let me break it down to you. And, NO, C/C++ not going anywhere only getting more traction because AI/ML make every CPU cycle count.

Memory Leaks

Easy to explain this one. Memory is allocated but not cleaned. The worst case when it’s being allocated in some cycle so your app is just keeps eating your memory like Pacman until it consumes all available memory and crushes. But single allocation on initialization and not properly cleaned in the end can cause later issues as well. As OS can still think this area is still being reserved and keep that way for a while or until the next reboot.

Dangling pointers/references

Can cause runtime issues. Especially for function pointers, lambdas, callbacks where it’s not clear when to release the memory or how to pass the parameter (e.g. by reference/pointer or value).

Release optimizations

Any reference/pointer can be optimised in release mode. Especially annoying case when it’s reference on a function. What is cleaned in Debug mode can be reused later but not in Release mode.

Undefined Behavior

What looks like a bug in compiler usually is undefined behavior. You don’t expect your function reference to be optimized out but it is – read undefined behavior.

Segmentation Faults

When restricted memory segment is accessed by a pointer usually causes SIGSEGV if a pointer == NULL, for example. In general it happens when you violate memory protection rules.

Bad Access (EXC_BAD_ACCESS)

Specific to MacOS. Wrong memory or data structure is accessed. For instance your pixel buffer has one format but you access it with different type can cause that.

SIGABRT

Can happen when you clean resource that’s being used.

Mitigation practices

How to debug? Watch you linter warnings (treat them as errors if you will). Write automated test for critical features. Keep Release with debug info next to you and use it in production. Use global handlers to intercept crashes and create a dump when it happens. And let the God bless you!

Yours,

VR


Discover more from Viacheslav Romanov

Subscribe to get the latest posts sent to your email.