Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I force my code to universally seg fault? [duplicate]

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.

like image 583
Erich Avatar asked Jul 16 '17 03:07

Erich


2 Answers

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:

?

.

like image 165
effbiae Avatar answered Nov 15 '22 01:11

effbiae


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.

like image 1
hedgar2017 Avatar answered Nov 15 '22 02:11

hedgar2017