2010-04-20 101 views
1

我目前正在处理一个处理People类对象向量的项目。该程序编译并运行得很好,但是当我使用调试器时,它会在试图用PersonWrangler对象做任何事情时死亡。我目前有三个不同的课程,一个是人,一个是集体处理所有人的personwrangler,一个是处理游戏输入和输出的游戏课程。C++中的向量错误

编辑:我的基本问题是了解为什么它会在调用outputPeople时死去。另外我想了解为什么我的程序完全按照它应该的方式工作,除非我使用调试器。 outputPeople函数以我想要的方式工作。

编辑2:调用堆栈有3个坏呼叫它们是:

  1. 的std ::矢量> ::开始(这= 0xbaadf00d)
  2. 的std ::矢量> ::大小(此= 0xbaadf00d )
  3. PersonWrangler :: outputPeople(此= 0xbaadf00d)

相关的代码:

class Game 
{ 
public: 
    Game(); 
    void gameLoop(); 
    void menu(); 
    void setStatus(bool inputStatus); 
    bool getStatus(); 
    PersonWrangler* hal; 
private: 
    bool status; 
}; 

它调用outputPeople它立即死于baadf00d错误。

void Game::menu() 
{ 
    hal->outputPeople(); 
} 

其中Hal是PersonWrangler型

class PersonWrangler 
{ 
public: 
    PersonWrangler(int inputStartingNum); 
    void outputPeople(); 
    vector<Person*> peopleVector; 
    vector<Person*>::iterator personIterator; 
    int totalPeople; 
}; 

和outputPeople功能的目标被定义为

void PersonWrangler::outputPeople() 
{ 
    int totalConnections = 0; 
    cout << " Total People:" << peopleVector.size() << endl; 
    for (unsigned int i = 0;i < peopleVector.size();i++) 
    { 
     sort(peopleVector[i]->connectionsVector.begin(),peopleVector[i]->connectionsVector.end()); 
     peopleVector[i]->connectionsVector.erase(unique (peopleVector[i]->connectionsVector.begin(),peopleVector[i]->connectionsVector.end()),peopleVector[i]->connectionsVector.end()); 
     peopleVector[i]->outputPerson(); 
     totalConnections+=peopleVector[i]->connectionsVector.size(); 
    } 
    cout << "Total connections:" << totalConnections/2 << endl; 
} 

其中Hal是初始化

Game::Game() 
{ 
    PersonWrangler* hal = new PersonWrangler(inputStartingNum); 
} 
+0

你的问题是什么? – 2010-04-20 21:19:27

+0

连接矢量在哪里? – 2010-04-20 21:20:17

+0

你有什么理由使用这么多的指针?原始指针的使用在C++中是不鼓励的。 – 2010-04-20 21:21:24

回答

6

0xBAADFOOD是一个magic number提醒你,你正在处理未初始化的内存。从堆栈跟踪中,我们看到thisPersonWrangler::outputPeople中无效。因此hal没有指向有效的PersonWrangler(也就是说,假设第4帧是对Game::menu的调用)。要自己解决这类问题,请逐步执行代码,从Game::Game()开始,随时检查Game::hal,查看可能出现的问题。

Game::Game,hal是一个局部变量shadowsGame::hal。当Game::Game退出时,此hal超出范围并泄漏内存,而Game::hal保持未初始化状态。你想要的是:

Game::Game() 
{ 
    hal = new PersonWrangler(inputStartingNum); 
} 

调试器填充未初始化的内存与幻数,以便更容易发现错误。在生产版本中,内存中没有特别的东西;未初始化内存的内容未定义,并可能保存有效值。这就是为什么生成构建可能不会在调试构建时失败的原因。

1

你初始化hal指向一个实际的PersonWrangler对象?

创建指针不会将其指向实际对象,除非您明确地指定它。您可能希望在构建时将PersonWrangler传递给您的游戏,或让游戏构造函数使用new创建PersonWrangler。如果您选择后者,请务必在您的PersonWrangler delete处,可能位于游戏解构器中。