Alex Rivera | Logout

What can cause segmentation faults in C++?

Asked 2011-08-03T08:22:53.860
48

I noticed there's not question with a list of common causes of segmentation faults in C++, so I thought I'd add it.

Naturally it's community Wiki, since there's no one correct answer.

I think this might be useful for newer programmers learning C++, feel free to close it if you disagree.

Edit
Report

2 Answers

6

Dereferencing NULL pointers.

#include <cstddef> //For NULL.
int* p1 = NULL; //p1 points to no memory address
*p1 = 3; //Segfault.
answered 2011-08-03T08:27:51.600
6

Many of the ways to 'segfault' C++ aren't necessarily guaranteed to happen, in fact, that is the case with most of the examples posted here. It's merely good luck (or bad luck, depending on how you look at it!) if you can perform these operations without a segfault occuring.

That is actually one of the things in C++ that separates it from other languages; undefined behaviour. Whereas in Java or C# you might get an 'InvalidOperationException' or similar, which is guaranteed to happen when these operations are performed; in C++, the standard just says 'undefined behaviour', which is basically luck of the draw, and you never want that to happen.

answered 2011-08-03T08:33:10.143

Your Answer