代码之家  ›  专栏  ›  技术社区  ›  shuttle87 Bhargav Boda

调用C++方法时的Sebug

  •  0
  • shuttle87 Bhargav Boda  · 技术社区  · 15 年前

    class History{
     public:
     bool test_history();
    };
    bool History::test_history(){
        std::cout<<"test"; //this line never gets executed
        //more code goes in here
        return true;
    }
    
    
    class Game{
     private:
        bool some_function();
     public:
        History game_actions_history;
    
    };
    
    
    bool Game::some_function(){
    
      return game_actions_history.test_history();
    
    }
    

    任何提示或建议都将不胜感激!

    4 回复  |  直到 15 年前
        1
  •  4
  •   wheaties    15 年前

    据我所知,你显示的代码没有问题。但是,segfaults通常是一个很好的迹象,表明您的内存已损坏。它发生在你所展示的以外的其他地方,只会影响这里的代码。我会看看你处理数组、指针或任何手动内存交互的任何地方。

        2
  •  4
  •   NomeN    15 年前

    我用过 valgrind 成功地解决了很多问题。

    你有没有试过用SEGDB故障导致的堆芯转储来运行gdb?来自man gdb:

    gdb program core
    

    要创建coredump,您可能必须设置:

    ulimit -c unlimited
    
        3
  •  1
  •   Matthieu M.    15 年前

    在黑暗中拍摄。 (Game*)this NULL

        4
  •  1
  •   user48956    15 年前

    代码很好,但示例太不完整,无法说明问题所在。我有一些建议:

    Game::Game()               { cerr << this << " Game::Game" << endl; }
    Game::Game(Game const&)    { cerr << this << " Game::Game(Game const&)" << endl; }
    Game::~Game()              { cerr << this << " Game::~Game" << endl; }
    bool Game::some_function() { cerr << this << " Game::some_function()" << endl; ... }
    

    这将揭示:

    • 错误/删除的类指针。

    第二,对于调试,我强烈建议将打印输出发送到cerr而不是cout。cout在输出之前通常是缓冲的(为了效率),cerr不是(至少以前是这样)。如果您的程序在没有执行错误处理程序的情况下退出,在退出时,等等,如果输出没有缓冲并立即打印,则更有可能看到输出。

    其他一些可能性包括:

    • 堆栈溢出:由于深度递归,您在堆栈上分配了大量内存,或者正在将包含大量数据数组的对象分配为局部变量(即未创建的或包含new或malloc的堆))
    • 损坏的类vtable(通常只可能由于生成工具中的依赖项错误),
    • 损坏的对象vtable指针:可能是由于误用指针:使用指向已删除内存的指针,或错误地写入正在使用的地址。在您的示例中不太可能,因为没有虚拟函数。
    • 维护对已删除堆栈上分配的对象的指针或引用:上面的打印输出代码将揭示这种情况。
        5
  •  -1
  •   sethuraman    4 年前

    我很好奇,因为您已经在Game类的private中定义了一些函数()。所以上面提到的代码结构也会抛出错误。