Segmentation fault (core dumped)
Segmentation fault (core dumped) in C++ means your C++ program attempted to access an invalid memory address that it does not have permission to read or write. Usually a dangling pointer, null pointer dereference, or buffer overrun.
How do I fix Segmentation fault (core dumped)?
To fix Segmentation fault (core dumped) in C++, locate the line causing the error and check the values right before it runs. Most occurrences happen because of returning a string_view or const char* to a temporary std::string. Apply a defensive check or safe fallback, make sure collections or objects exist before access, and verify return values from upstream functions.
What does Segmentation fault (core dumped) mean?
The operating system sends SIGSEGV when a thread tries to access memory outside its valid virtual address space. In modern C++, this frequently occurs when holding pointers or string_views to temporary objects that were deallocated when their containing expression ended.
Why does Segmentation fault (core dumped) happen?
1. Returning a string_view or const char* to a temporary std::string
The temporary std::string is destroyed at the end of the statement, leaving the pointer pointing to freed stack memory.
Breaks
std::string_view getGreeting() {
return std::string("Hello"); // destroyed on return!
}Works
std::string getGreeting() {
return "Hello"; // return by value
}2. Dereferencing a nullptr or failed dynamic_cast
Calling a member function through a null pointer crashes immediately.
Breaks
Car* c = dynamic_cast<Car*>(vehicle);
c->drive(); // crashes if vehicle was not a Car!Works
if (Car* c = dynamic_cast<Car*>(vehicle)) {
c->drive();
}How to find it in your own code
Avoid returning views or raw pointers to local stack variables. Check dynamic_cast return values against nullptr before invoking methods. Use AddressSanitizer (-fsanitize=address) during testing to pinpoint invalid memory accesses.
Still not sure why yours breaks?
Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.