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?
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)
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.
Stack smashing in X86_64 leads to Segmentation 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.
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); }
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