2016-06-25 65 views
3

我想弄清楚一個小錯誤代碼後段錯誤的根本原因。讓我們從這個簡化版本的代碼,它運行沒有問題開始:C++指針和類層次結構導致段錯誤難題

#include <iostream> 
#include <string> 
#include <vector> 

class GameObject { 
    public: 
     virtual void update(); 
     void addChild(GameObject* child); 

     GameObject* parent; 
     std::vector<GameObject*> children; 
     int x; 
     int y; 
}; 

class Player : public GameObject { 
    public:  
     void growTail(); 
     void update(); 
}; 

class TailNode : public GameObject { 
    public:  
     void addTo(GameObject* parent); 
     void update(); 
     // UPDATE AFTER ANSWER IS CLEAR: this was in original codebase and it was causing the segfault 
     GameObject* parent; 
}; 

void GameObject::addChild(GameObject* child) { 
    this->children.push_back(child); 
    child->parent = this; // <- can't do this in full codebase, causes segfault later 
} 

void GameObject::update() { 
    for (GameObject* child : children) { 
      child->update(); 
    } 
} 

void Player::update() { 
    GameObject::update(); 
    std::cout << "Player at: [" 
     << std::to_string(x) 
     << std::to_string(y) 
     << "]" 
     << std::endl; 
} 

void Player::growTail() { 
    TailNode* tail = new TailNode(); 
    tail->addTo(this); 
} 

void TailNode::update() { 
    GameObject::update(); 
    std::cout << "Tail parent at: [" 
     << std::to_string(parent->x) // <- if parent is set inside GameObject::addChild, this segfaults in full codebase 
     << std::to_string(parent->y) 
     << "]" 
     << std::endl; 
} 

void TailNode::addTo(GameObject* parent) { 
    parent->addChild(this); 
    // this->parent = parent; <-- have to do this to avoid segfault in full codebase 
} 

int main() { 
    Player* player = new Player(); 
    player->x = 10; 
    player->y = 11; 
    player->growTail(); 
    player->update(); 
} 

現在,在遊戲源本身,它確實段錯誤,因爲顯然尾節點得到一個壞父母。

當我移動child->parent = this;遠離GameObject::addChild並使用this->parent = parent;TailNode::addTo,它的工作原理。

我猜測它與指針和我濫用它們的方式有關。

您可以在https://github.com/spajus/sdl2-snake/tree/tail_working 找到完整的工作代碼庫提交,打破它:https://github.com/spajus/sdl2-snake/commit/4e92e9d6823420ce7554f2b6d7d19992c48d4acc

我上編譯和OS X 10.11.5運行它,

Apple LLVM version 7.3.0 (clang-703.0.31) 
Target: x86_64-apple-darwin15.5.0 
Thread model: posix 

代碼依賴SDL2以及它的一些擴展。

示例編譯命令:

$XCODE/XcodeDefault.xctoolchain/usr/bin/c++ \ 
-I/Library/Frameworks/SDL2.framework/Headers \ 
-I/Library/Frameworks/SDL2_image.framework/Headers \ 
-I/Library/Frameworks/SDL2_mixer.framework/Headers \ 
-I/Library/Frameworks/SDL2_ttf.framework/Headers \ 
-I$HOME/Dev/sdl2-snake/include \ 
-Wall -Wextra -pedantic -std=c++11 \ 
-Wall -Wextra -pedantic -std=c++11 \ 
-g -g -o CMakeFiles/Snake.dir/src/main.cpp.o \ 
-c $HOME/Dev/sdl2-snake/src/main.cpp 

我知道你會建議使用智能指針,而不是赤裸裸的,你可能是正確的,但在這裏,我只是覺得好玩和好奇地找出爲什麼它打破這種方式。它可能很難重現(儘管有構建腳本),但是一個經驗豐富的C++開發人員可能會立即發現問題。另外,我很欣賞代碼審查和改進建議,我的C++技能接近於零,因爲自十多年前我從大學以來就沒有做過任何事情。

回答