在哪里寻找分段故障?

时间:2014-01-01 03:04:10

标签: c++ 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_animationqueue_animation都是班级Animation的指针 另请注意,Animation::update()内是一个函数指针,它在构造函数中传递给Animation。

如果您需要查看所有代码,则会超过here

修改

我将代码更改为使用bool:

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

2 个答案:

答案 0 :(得分:6)

分段错误的一些原因:

  1. 取消引用未初始化或指向NULL的指针
  2. 您取消引用已删除的指针
  3. 您在分配的内存范围之外写入(例如,在数组的最后一个元素之后)

答案 1 :(得分:1)

使用您的软件运行valgrind(警告,它确实减慢了速度)。很可能内存已经被某种方式覆盖了。 Valgrind(和其他工具)可以帮助追踪这些问题,但不是所有问题。

如果它是一个大型程序,这可能变得非常困难,因为一切都是可疑的,因为任何东西都可以破坏内存中的任何东西。您可以尝试通过以某种方式限制程序来最小化运行的代码路径,并查看是否可以解决问题。这有助于减少可疑代码的数量。

如果您的代码的先前版本没有问题,请查看是否可以恢复到该代码,然后查看更改的内容。如果您正在使用git,它有一种方法可以将搜索平分为首次出现故障的修订版。

警告,这种事情是C / C ++开发人员的祸根,这也是Java等语言“更安全”的原因之一。

您可能只是开始查看代码并查看是否可以找到看似可疑的内容,包括可能的竞争条件。希望这不会花费太多时间。我不想吓到你,但这些错误可能是最难追踪的。

相关问题