8

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.

Erich
  • 1,902
  • 1
  • 17
  • 23

3 Answers3

10

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:

?

.

effbiae
  • 1,087
  • 1
  • 7
  • 22
  • *What is a segmentation fault* https://stackoverflow.com/questions/2346806/what-is-a-segmentation-fault – effbiae Jul 16 '17 at 05:38
1

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.

hedgar2017
  • 1,425
  • 3
  • 21
  • 40
1

C language itself doesn't specify anything about segmentation fault. It says the behavior is undefined if you try to access an invalid memory. Segmentation fault or SIGSEGV is a common signal from some underlying platforms to denote invalid memory access. But obviously the underlying platform can decide how it want to behave on such error.

Having saying that, if you are strict about C and "Preferrably regardless of platform" manner then there is no way to force this which will work on every platform on the world.

taskinoor
  • 45,586
  • 12
  • 116
  • 142