How to avoid SIGSEGV?

孤街浪徒 提交于 2019-12-11 09:00:47

问题


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_ptr or std::shared_ptr for 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::atomic or 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

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