I was making a game using Code::Blocks, and came across the Segmentation fault error. 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. I ran the debugger and it gave me the error at the line return image;
from the getImage()
method below.
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
.
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];
:
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
?
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.
In any case, you should at least confirm you aren't dereferencing a null pointer here
sprites[i]->getImage()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.