Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I cause a seg fault?

Tags:

OK for whatever reason I'm having trouble causing a seg fault. I want to produce one so that I can use gdb to see how to debug one. I have tried both examples from the Wikipedia article yet neither work.

The first one:

char *s = "Hello World!"; *s = 'H'; 

And the second example:

int main(void)  {     main(); } 

EDIT: I'm using Ubutnu 9.10 and g++ as my compiler. Can anyone show me some code that is guaranteed to segfault?

like image 929
Bob Dylan Avatar asked Jan 11 '10 22:01

Bob Dylan


People also ask

How do you trigger a segmentation fault?

The following are some typical causes of a segmentation fault: Attempting to access a nonexistent memory address (outside process's address space) Attempting to access memory the program does not have rights to (such as kernel structures in process context) Attempting to write read-only memory (such as code segment)

How do you avoid a seg fault?

Use a #define or the sizeof operator at all places where the array length is used. Improper handling of NULL terminated strings. Forgetting to allocate space for the terminating NULL character. Forgetting to set the terminating NULL character.

Is stack smashing a seg fault?

Stack smashing in X86_64 leads to Segmentation fault .

Can you catch a seg fault?

You can't catch segfaults. Segfaults lead to undefined behavior - period (err, actually segfaults are the result of operations also leading to undefined behavior.


1 Answers

It impossible to try and reliable do it dereferencing pointers.
This is because how the application handles memory can vary from compiler to compiler also across the same compiler with different options (debug/release mode handled differently).

What you can do is explicitly raise the segfault using a signal:

#include <signal.h>  int main() {     raise(SIGSEGV); } 
like image 129
Martin York Avatar answered Sep 19 '22 09:09

Martin York