The obvious answer is “undefined behavior”, but this begs
the question for an unexperienced programmer, and some types of
undefined behavior are much less likely to cause a segmentation fault
(or another type of crash) than others. The most frequent causes of
segmentation faults are generally pointer related: dereferencing an
uninitialized pointer, a null pointer, or a previously freed pointer;
accessing beyond the end (or in front of the beginning, but that's less
frequent) of an object (array or other); using the results of an illegal
pointer cast (static_cast
to a derived type, when the object doesn't
actually have that type, or most reinterpret_cast
); etc.
Perhaps the most important point to keep in mind here, however, is that
in general, these are not guaranteed to cause a segmentation fault, and
that often, the segmentation fault that they cause will only occur
sometime later, in a completely unrelated operation. Thus, writing
beyond the end of a local array will usually “work”,
but will modify whatever happens to follow the array on the stack: some
other local variable (modifying the vptr
of an object on the stack
may lead to a segmentation fault when you attempt to call a virtual
function on the object), the frame pointer of the calling function
(which will probably cause a segmentation fault in that function, after
you've returned), or the return address (which may cause all sorts of
strange behavior—a segmentation fault or an illegal instruction
trap are probably the best that can occur). Writing beyond the end of
freed memory, or through an already freed pointer, can corrupt the free
space arena, causing a segmentation fault in a much (sometime much,
much) later allocation or free; it can also modify some other, totally
unrelated object, corrupting its vptr
or some other pointer in the
object, or just some random data—again, a segmentation fault is
probably the best possible result (far preferrable to continuing with
corrupted data).