[英]Program received signal SIGSEGV, Segmentation fault in getter method
I was making a game using Code::Blocks, and came across the Segmentation fault error. 我当时使用Code :: Blocks制作游戏,并遇到了Segmentation Fault错误。 I have looked through other questions here and couldn't find anything that helped.
我在这里浏览了其他问题,找不到任何帮助。 I have a
Sprite
class that represents the basic objects in the game and a Window
class that controls the display to the screen of the game. 我有一个
Sprite
类,它表示游戏中的基本对象,还有一个Window
类,用于控制游戏屏幕的显示。 I ran the debugger and it gave me the error at the line return image;
我运行调试器,它在行
return image;
处给了我错误return image;
from the getImage()
method below. 来自下面的
getImage()
方法。
SDL_Surface* Sprite::getImage() {
return image;
}
I call the following setImage()
method in the constructor for Sprite
, and I verified that SDL_ConvertSurface
did not return NULL
. 我在
Sprite
的构造函数中调用了以下setImage()
方法,并验证了SDL_ConvertSurface
没有返回NULL
。
void Sprite::setImage(string path) {
SDL_Surface* loadedSurface = IMG_Load( path.c_str() );
if( loadedSurface == NULL ) {
printf( "Unable to load image %s! SDL_image Error: %s\n", path.c_str(), IMG_GetError() );
} else {
image = SDL_ConvertSurface( loadedSurface, surface->format, NULL );
if( image == NULL ) {
printf( "Unable to optimize image %s! SDL Error: %s\n", path.c_str(), SDL_GetError() );
}
SDL_FreeSurface( loadedSurface );
}
}
I call the method getImage()
in mainloop()
of Window
, as shown below, where sprites
is declared as Sprite* sprites[10];
我在
Window
mainloop()
中调用方法getImage()
,如下所示,其中将sprites
声明为Sprite* sprites[10];
: :
void Window::mainloop() {
bool quit = false;
SDL_Event e;
while( !quit ) {
while( SDL_PollEvent( &e ) != 0 ) {
if( e.type == SDL_QUIT ) {
quit = true;
}
}
SDL_FillRect( screenSurface, NULL, SDL_MapRGB( screenSurface->format, red, green, blue ) );
for (int i = 0; i < spritesNum; i++) {
SDL_BlitScaled( sprites[spritesNum]->getImage() , NULL, screenSurface, sprites[spritesNum]->getRect() );
}
SDL_UpdateWindowSurface( window );
}
}
You are probably indexing out of range here 您可能在这里索引超出范围
for (int i = 0; i < spritesNum; i++) {
SDL_BlitScaled( sprites[spritesNum]->getImage() , NULL, screenSurface, sprites[spritesNum]->getRect() );
}
I assume you wanted to use your counter i
? 我假设你想用你的计数器
i
?
for (int i = 0; i < spritesNum; i++) {
SDL_BlitScaled( sprites[i]->getImage() , NULL, screenSurface, sprites[i]->getRect() );
}
Otherwise if your array sprites
is of length spritesNum
you are indexing out of range, and doing so spritesNum
number of times. 否则,如果您的数组
sprites
的长度为spritesNum
,则索引超出范围,并且执行spritesNum
次数。
In any case, you should at least confirm you aren't dereferencing a null pointer here 无论如何,您至少应该确认您没有在这里取消引用空指针
sprites[i]->getImage()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.