[英]Program SegFaults right after a Constructor. C++
我目前在我正在編寫的程序上有一個小問題,它在構造函數之后才出現segFaults。
這是一些代碼:
void GameEngine::createMap(std::vector<std::string> &parse)
{
int x;
int y;
std::string strx;
std::string stry;
strx = parse.at(0);
stry = parse.at(1);
x = atoi(strx.c_str());
y = atoi(stry.c_str());
std::cout << "okokok" << std::endl;
//_gMap is a Graphmap*;
this->_gMap = new GraphMap(x, y);
std::cout << "okokokabc" << std::endl;
}
當我連接的服務器向我發送“ msz XY \\ n”時,createMap()是一個函數,肯定會被調用。 有效的XY。
所以這是一個調用我的類的(GraphMap)構造函數的函數。 X和Y為有效數字
這是GraphMap類。
.hh
#ifndef GRAPHMAP_HH_
#define GRAPHMAP_HH_
class GameEngine;
class GraphMap
{
private:
int _height;
int _width;
int _squareSize;
public:
GraphMap(int, int);
~GraphMap();
void draw(SDL_Renderer *);
};
#endif
和.cpp:
#include "GameEngine.hh"
#include "GraphMap.hh"
GraphMap::GraphMap(int width, int height)
{
std::cout << "testouilleee1" << std::endl;
_width = width;
std::cout << "testouilleee2" << std::endl;
_height = height;
std::cout << "testouilleee3" << std::endl;
_squareSize = 1000 / width;
std::cout << "testouilleee4" << std::endl;
}
GraphMap::~GraphMap() {}
void GraphMap::draw(SDL_Renderer *renderer)
{
int i;
int j;
for(i = 1 ; i <= _width ; i++)
{
for (j = 1 ; j <= _height ; j++)
{
SDL_Rect rect;
rect.x = ((i - 1) * _squareSize);
rect.y = ((j - 1) * _squareSize);
rect.w = _squareSize - 1;
rect.h = _squareSize - 1;
SDL_SetRenderDrawColor(renderer, 0, 255, 0, 255);
SDL_RenderFillRect(renderer, &rect);
}
j = 1;
}
}
我不明白的是,輸出是:
$ ./run.sh
okokok
testouilleee1
testouilleee2
testouilleee3
testouilleee4
./run.sh: line 12: 10414 Segmentation fault (core dumped) ./zappy_graph 127.0.0.1 4242
這意味着它將轉到構造函數的最后一行,但隨后出現segFaults,並且不會打印我無法理解的“ okokokabc”
以下是來自GDB的一些調試信息:
0x0000000000404556 in GameEngine::createMap (this=0x0, parse=...) at GameEngine.cpp:90
90 this->_gMap = new GraphMap(x, y);
(gdb) bt
#0 0x0000000000404556 in GameEngine::createMap (this=0x0, parse=...) at GameEngine.cpp:90
#1 0x000000000040561b in Command::msz (this=0x712360, cmd=..., game=0x0) at Command.cpp:32
#2 0x000000000040647c in Command::Parse (this=0x712360, command=..., game=0x0) at Command.cpp:138
#3 0x000000000040949b in Socket::selectSocket (this=0x7120a0) at Socket.cpp:67
#4 0x000000000040441e in GameEngine::update (this=0x712010) at GameEngine.cpp:58
#5 0x00000000004046f0 in GameEngine::run (this=0x712010) at GameEngine.cpp:110
#6 0x000000000040968e in main (ac=1, av=0x7fffffffdd78) at main.cpp:22
(gdb) print x
$1 = 20
(gdb) print y
$2 = 20
如果您需要更多信息/代碼,請告訴我,我會盡快將其發布。
GDB顯示GameEngine
地址為0x0
:
GameEngine::createMap (this=0x0...
所以問題在於,由於某種原因,GameEngine指針是錯誤的(未初始化或未損壞)。
請注意,該指針似乎至少來自
Command::Parse (this=0x712360, command=..., game=0x0)
(我想最后一個參數是GameEngine本身嗎?)
還要注意下面的一些行中有正確的GameEngine
對象:
GameEngine::update (this=0x712010) at GameEngine.cpp:58
如果您的程序中只有一個GameEngine
(我假設是這種情況),那么這意味着GameEngine
地址在GameEngine::update()
和Command::Parse()
之間以某種方式丟失了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.