I think the question says it all. An example covering most standards from C89 to C11 would be helpful. I though of this one, but I guess it is just undefined behaviour:
The standard only mentions undefined behavior. It knows nothing about memory segmentation. Also note that the code that produces the error is not standard-conformant. Your code cannot invoke undefined behavior and be standard conformant at the same time.
Nonetheless, the shortest way to produce a segmentation fault on architectures that do generate such faults would be:
int main()
{
*(int*)0 = 0;
}
Why is this sure to produce a segfault? Because access to memory address 0 is always trapped by the system; it can never be a valid access (at least not by userspace code.)
Note of course that not all architectures work the same way. On some of them, the above could not crash at all, but rather produce other kinds of errors. Or the statement could be perfectly fine, even, and memory location 0 is accessible just fine. Which is one of the reasons why the standard doesn't actually define what happens.
It's hard to define a method to segmentation fault a program on undefined platforms. A segmentation fault is a loose term that is not defined for all platforms (eg. simple small computers).
Considering only the operating systems that support processes, processes can receive notification that a segmentation fault occurred.
Further, limiting operating systems to 'unix like' OSes, a reliable method for a process to receive a SIGSEGV signal is kill(getpid(),SIGSEGV)
As is the case in most cross platform problems, each platform may (an usually does) have a different definition of seg-faulting.
But to be practical, current mac, lin and win OSes will segfault on
*(int*)0 = 0;
Further, it's not bad behaviour to cause a segfault. Some implementations of assert()
cause a SIGSEGV signal which might produce a core file. Very useful when you need to autopsy.
What's worse than causing a segfault is hiding it:
try
{
anyfunc();
}
catch (...)
{
printf("?\n");
}
which hides the origin of an error and all you've got to go on is:
?
.
The simplest form considering the smallest number of characters is:
++*(int*)0;
raise()
can be used to raise a segfault:
raise(SIGSEGV);