How to Track and Fix Memory-Related Errors
Introduction
Greetings and welcome to the first technical article in my humble blog ✨.
Today we’ll discuss an interesting topic in programming: how to debug a program to catch memory-related errors (segmentation fault) in both C/C++ using core files. We’ll explain what they are, how to get them generated, and more — all in this article. Follow along.
What Are Core Files?
Core files are simply files that get generated when a memory-related problem occurs in a program, causing it to crash (like buffer overflow, stack overflow, etc.). These are problems related to unauthorized access to memory or the program’s memory section running out for any reason. So, what happens and why are these files generated? Good question. Behind the scenes, when an issue occurs (for example, calling a recursive function without a base case), the program will crash, and the memory state at the moment of the crash is saved.
How Do We Generate Them?
To generate core files on Linux, use the following command:
ulimit -c unlimitedThe -c flag refers to core files, telling the kernel to generate an unlimited number of core files. What’s next? Now, set the name pattern for generated core files, this must be run as root:
echo "./core" > /proc/sys/kernal/core_patternYou can use any name, but for clarity, use “core” or “mem_junk.”
The Most Important Step Before Compile
For this method to work, and for the GNU Debugger (gdb) to give you useful information, you must pass the -g flag at compile time:
g++ main.cpp -g -o mainThis flag instructs the compiler to embed debugging information in the executable.
The Final Step
After setting up everything, the last thing is to analyze the generated core files to diagnose and fix the error. Use gdb as follows:
gdb ./main ./coreYou pass it the program binary and the core file produced when the program crashed. The debugger will analyze the core file and provide a basic explanation of the crash on the screen.
Conclusion
That’s all for today. I hope you found this article helpful and beneficial. Until we meet again, stay safe ✨🖤!