问题
I am writing a client-server daemon which have to accept and translate specific message formats, check them submit to submit all activity to DB. Program is multithreaded. So, I started to work, and began to get SIGSEGV in some cases. So I had to redesign my program and start all over. I am wondering, if there are any "best practices" or tips on how to minimize risk of SIGSEGV ? I know, that each pointer should be checked before usage and NULLED after deleting, but if there any high level, design tips ?
P.S. Sorry, if my question if quite dummy, but I googled for this topic and did not find any reasonable articles on this topic. All your opinions are appreciated.
回答1:
Concurrency can be the source of lots of issues, in several different ways, and SIGSEV is one of the issues.
A beginner might pass a pointer Data* p; to two threads, and before exiting make them execute this code.
if(p){
delete p->data;
delete p;
p = NULL;
}
You just need both threads to see p as non null, be preempted to have a SIGSEV scenario. Using standard containers or smart pointers as @jogojapan pointed out can mitigate this issues.
回答2:
Major sources of segmentation faults are
- Uninitialized pointers (or uninitialized variables in general)
- Out-of-bound access to arrays
- Poorly coded pointer arithmetics
The main strategies to deal with this include:
- Always initialize your variables, in particular pointers
- Avoid naked pointers (prefer smart pointers, such as
std::unique_ptrorstd::shared_ptrfor pointers that own data, and use iterators into standard containers if you want to merely point at stuff) - Use standard containers (e.g.
std::vector) instead of arrays and pointer arithmetics
As mentioned in the comments, poorly coded concurrency or parallelization can cause segmentation faults (and many other problems), in a similar way as uninitialized variables can, because they may cause the value of a variable to be altered unexpectedly. General strategies to deal with this include:
- Avoid shared data – prefer messaging / queues for inter-thread communication
- If you have shared data, and at least one thread writes into those data, use mutexes,
std::atomicor similar for protection
However, both may in some cases mean that you loose significant performance benefits. Getting parallel algorithms right is a matter of careful analysis and design.
来源:https://stackoverflow.com/questions/16768532/how-to-avoid-sigsegv