C++ Creating a SIGSEGV for debug purposes

你说的曾经没有我的故事 提交于 2019-12-06 03:23:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!