Joel Joel - 1 year ago 111
C Question

Valgrind: Deliberately cause segfault

This is a mad-hack, but I am trying to deliberately cause a segfault at a particular point in execution, so valgrind will give me a stack trace.

If there is a better way to do this please tell me, but I would still be curious to know how to deliberaly cause a segfault, and why my attempt didn't work.

This is my failed attempt:

long* ptr = (long *)0xF0000000;
ptr = 10;

I thought valgrind should at least pick up on that as a invalid write, even if it's not a segmentation violation. Valgrind says nothing about it.

Any ideas why?


Answer accepted, but I still have some up-votes for any suggestions for a more sane way to get a stack trace...

Answer Source

Are you missing a * as in *ptr = 10? What you have won't compile.

If it does, somehow, that of course won't cause a seg-fault, since you're just assigning a number. Dereferencing might.

Assuming dereferencing null on your OS results in a segfault, the following should do the trick:

inline void seg_fault(void)
    volatile int *p = reinterpret_cast<volatile int*>(0);
    *p = 0x1337D00D;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download