问题描述
我正在编写一个客户端 - 服务器守护进程,它必须接受并翻译特定的消息格式,检查它们是否提交所有活动到DB。程序是多线程的。所以,我开始工作,并开始得到SIGSEGV在某些情况下。所以我不得不重新设计我的程序,从头开始。
我想知道,如果有任何最佳做法或提示如何最大限度地降低SIGSEGV的风险?
我知道,每个指针在使用之前应该检查,在删除之后应该检查NULLED,但是如果有任何高级别的设计提示?
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 ?
对不起,如果我的问题,如果很虚假,但我googled这个话题,没有找到任何合理的文章这个话题。
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.
推荐答案
分段错误的主要来源是
- 未初始化的指针(或一般为未初始化的变量)
- 超出对数组的访问
- 指针算术
处理这些的主要策略包括:
The main strategies to deal with this include:
- 始终初始化您的变量,特别是指针
- 避免裸指针(更喜欢智能指针,例如
std :: unique_ptr
或std :: shared_ptr
用于拥有数据的指针,如果只想在 li>
- 使用标准容器(例如
std :: vector
)而不是数组和指针算术
- Always initialize your variables, in particular pointers
- Avoid naked pointers (prefer smart pointers, such as
std::unique_ptr
orstd::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:
- 避免共享数据–喜欢用于线程间通信的消息/队列
- 如果您有共享数据,并且至少有一个线程写入这些数据,请使用mutexes
std :: atomic
或类似用于保护
- 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.
这篇关于如何避免SIGSEGV?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!