在哪里查找分段错误?
Where to look for Segmentation fault?
我的程序只是偶尔会得到一个Segmentation fault: 11
,我一辈子都想不通。我在C++和指针领域了解不多,所以我应该寻找什么样的东西?
我知道这可能与我正在使用的某些函数指针有关。
我的问题是什么样的事情会产生分段错误?我对此感到非常迷茫,我已经浏览了我认为可能导致此问题的所有代码。
我正在使用的调试器是 lldb,它显示此代码段中的错误:
void Player::update() {
// if there is a smooth animation waiting, do this one
if (queue_animation != NULL) {
// once current animation is done,
// switch it with the queue animation and make the queue NULL again
if (current_animation->Finished()) {
current_animation = queue_animation;
queue_animation = NULL;
}
}
current_animation->update(); // <-- debug says program halts on this line
game_object::update();
}
current_animation
和queue_animation
都是类Animation
的指针。
另请注意,Animation::update()
中有一个函数指针,该指针在构造函数中传递给动画。
如果您需要查看所有代码,请在此处结束。
编辑:
我将代码更改为使用布尔值:
void Player::update() {
// if there is a smooth animation waiting, do this one
if (is_queue_animation) {
// once current animation is done,
// switch it with the queue animation and make the queue NULL again
if (current_animation->Finished()) {
current_animation = queue_animation;
is_queue_animation = false;
}
}
current_animation->update();
game_object::update();
}
它没有任何帮助,因为我有时仍然会遇到分段错误。
编辑2:
修改了以下代码:
void Player::update() {
// if there is a smooth animation waiting, do this one
if (is_queue_animation) {
std::cout << "queue" << std::endl;
// once current animation is done,
// switch it with the queue animation and make the queue NULL again
if (current_animation->Finished()) {
if (queue_animation != NULL) // make sure this is never NULL
current_animation = queue_animation;
is_queue_animation = false;
}
}
current_animation->update();
game_object::update();
}
只是为了查看此函数何时会在没有任何用户输入的情况下输出。每次我遇到分段错误时,这都会在错误之前输出两次。这是我的调试输出:
* thread #1: tid = 0x1421bd4, 0x0000000000000000, queue = 'com.apple.main-thread, stop reason = EXC_BAD_ACCESS (code=1, address=0x0)
frame #0: 0x0000000000000000
error: memory read failed for 0x0
分段错误的一些原因:
- 取消引用未初始化或指向 NULL 的指针
- 取消引用已删除的指针
- 您在分配内存的范围之外写入(例如,在数组的最后一个元素之后)
用你的软件运行valgrind(警告,它确实会减慢速度)。内存很可能以某种方式被覆盖了。Valgrind(和其他工具)可以帮助追踪其中一些类型的问题,但不是全部。
如果它是一个大型程序,这可能会变得非常困难,因为一切都是可疑的,因为任何东西都可能损坏内存中的任何内容。您可以尝试通过以某种方式限制程序来最小化运行的代码路径,看看是否可以解决问题。这有助于减少可疑代码的数量。
如果您有以前版本的代码没有问题,请查看是否可以恢复到该版本,然后查看更改的内容。如果您使用的是 git,它有一种方法可以将搜索一分为二到首次发生故障的修订版中。
警告,这种事情是C/C++开发人员的祸根,这也是Java等语言"更安全"的原因之一。
您可能只是开始查看代码,看看是否可以找到看起来可疑的内容,包括可能的竞争条件。希望这不会花费太多时间。我不想吓到你,但这些类型的错误可能是最难追踪的。
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 为什么我使用 std::copy() 收到运行时错误(分段错误)?
- 为什么我的代码包含错误分段错误(核心转储)?
- 为什么会出现此错误?- 分段错误(核心转储)
- 意外的运行时错误(分段错误)
- C++将文本文件读入数组,运行错误:分段错误
- mmap 错误:分段错误/指针无效错误
- 在我的代码中找不到错误....分段错误
- 错误:分段故障(核心转储)阵列
- 用string.h将错误分段到队列中
- c++字符串流转换错误:分段错误
- 为什么我的代码显示错误分段错误(核心转储)