I'm relatively new to C++ and I am learning it using SDL 2.0. I have encountered the following error when trying to draw a sprite using my Sprite class:
Exception thrown at 0x000000006C793659 (SDL2.dll) in SDDDDL2.exe: 0xC0000005: Access violation reading location 0xFFFFFFFFFFFFFFFF.
The following code is a stripped down version of the involved code in my Sprite class:
public:
SDL_Texture *image = NULL;
SDL_Rect rect;
void SetTexture(SDL_Texture *texture)
{
image = texture;
rect.x = 100; rect.y = 100; rect.w = 64; rect.h = 64;
}
void DrawSprite(SDL_Renderer *renderer)
{
SDL_RenderCopy(renderer,image,NULL,&rect); //Calling this causes the
//error
}
And the key code in my main game class "Game.cpp"
Sprite *testSprite = NULL;
SDL_Texture *testTex = NULL;
void LoadContent()
{
SDL_Surface *bmpSurface = SDL_LoadBMP("sprite.bmp");
testTex = SDL_CreateTextureFromSurface(renderer, bmpSurface);
testSprite = &Sprite(Vector2(100,100),Vector2(50,50)); // Just the
//constuctor, this is not affecting the issue
testSprite->SetTexture(testTex);
SDL_FreeSurface(bmpSurface);
}
void Draw ()
{
testSprite->DrawSprite(renderer); // Get the error when calling this
}
I know through testing that it is indeed the texture being passed into the SDL_RenderCopy function ( image ) that is causing the issue, as this does not happen if I call the function in Game.cpp file using the "testTex" image.
I also know that the texture used in the SDL_RenderCopy function is not NULL , as I used null checks before calling SDL_RenderCopy, and it called anyway.
I think the problem lies in this line: testSprite = &Sprite(Vector2(100,100), Vector2(50,50));
The address value that testSprite
gets assigned is invalid as soon as LoadContent()
returns.
Replace it with eg testSprite = new Sprite(Vector2(100,100),Vector2(50,50));
and re-run.
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.