I was wondering what the best way would be to reliably segmentation fault a piece of C code?
I'm fully aware that this is bad behavior, and should never be used in a piece of software, but I wanted to know how I could consistantly force it to happen.
EDIT: The answer I got was not what I originally was looking for, but is valuable in understanding why this question doesn't have a reliable answer.
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, and answer the EDIT2, 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:
?
.
Just try to read or write to an illegal memory location. For example:
memset(NULL, 1, 1);
Here you are writing a one to address 0, definitely illegal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With