How to debug a core in C/C++?

A process dumps core when it is terminated by the operating system due to a fault in the program. The most typical reason this occurs is that the program accessed an invalid pointer value like NULL or some value out of its memory area. As part of that process, the operating system tries to write debugging information to a file to allow us to analyze what happened.

Prerequisites

Installation Requirements:

  • Install GDB debugger: sudo apt-get install gdb (Ubuntu/Debian) or yum install gdb (CentOS/RHEL)
  • Enable core dumps: ulimit -c unlimited
  • Compile programs with debug symbols: gcc -g -o program program.c

How Core Dumps Work

When a program crashes, the operating system captures the memory state and saves it to a core file. This file contains −

  • Memory contents at the time of crash
  • Register values and stack trace
  • Information about the instruction that caused the fault

Example: Program That Generates Core Dump

Here's a simple program that will cause a segmentation fault −

#include <stdio.h>
#include <stdlib.h>

int main() {
    int *ptr = NULL;
    
    printf("About to dereference NULL pointer...\n");
    
    /* This will cause segmentation fault and core dump */
    *ptr = 42;
    
    printf("This line will never execute\n");
    return 0;
}
About to dereference NULL pointer...
Segmentation fault (core dumped)

Debugging the Core Dump

The core is typically dumped to the current directory or /var/crash. To debug a core file, follow these steps −

Step 1: Compile with Debug Information

$ gcc -g -o crash_program crash_program.c

Step 2: Run the Program

$ ./crash_program

Step 3: Debug with GDB

$ gdb crash_program core

Common GDB Commands for Core Analysis

Command Description Example
bt Show stack trace (gdb) bt
info registers Display register values (gdb) info registers
list Show source code around crash (gdb) list
print variable Examine variable values (gdb) print ptr

Key Points

  • Always compile with -g flag for debugging symbols
  • Enable core dumps using ulimit -c unlimited
  • Use bt command first to see where the program crashed
  • Examine variables around the crash point to identify the cause

Conclusion

Core dumps are valuable for post-mortem debugging of crashed C programs. By using GDB with core files, you can quickly identify the exact location and cause of segmentation faults and other runtime errors.

Updated on: 2026-03-15T09:51:33+05:30

576 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements