问题
I am working on a lock-free shared variable class, and I want to be able to generate a SIGSEGV fault to see if my implementation works as I planned. I've tried creating a function that modifies a pointer and read it 100 times. I then call this function in both threads and have the threads run infinitely within my program. This doesn't generate the error I want. How should I go about doing this?
edit I don't handle segfaults at all, but they are generated in my program if I remove locks. I want to use a lock-less design, therefore i created a shared variable class that uses CAS to remain lockless. Is there are way that I can have a piece of code that will generate segfaults, so that i can use my class to test that it fixes the problem?
回答1:
#include <signal.h>
raise(SIGSEGV);
Will cause an appropriate signal to be raised.
回答2:
malloc + mprotect + dereference pointer
This mprotect man page has an example.
回答3:
Derefencing pointer to unallocated memory (at least on my system):
int *a;
*a = 0;
回答4:
Dereference an invalid pointer:
*((int*)0x8100000000000000) = 5;
来源:https://stackoverflow.com/questions/9457928/c-creating-a-sigsegv-for-debug-purposes