Reputation: 2018
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.
Upvotes: 1
Views: 2299
Reputation: 70027
Major sources of segmentation faults are
The main strategies to deal with this include:
std::unique_ptr
or std::shared_ptr
for pointers that own data, and use iterators into standard containers if you want to merely point at stuff)std::vector
) instead of arrays and pointer arithmeticsAs 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:
std::atomic
or similar for protectionHowever, both may in some cases mean that you loose significant performance benefits. Getting parallel algorithms right is a matter of careful analysis and design.
Upvotes: 3
Reputation: 22910
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.
Upvotes: 2