So, I'm trying to create a sprite class for my game however I can't seem to get it to work.
When trying to render my texture using SDL_RenderCopy() it causes a exception and my game crashes with the error :
Access violation reading location 0xDDDDDDDD.
When checking SDL_GetError() right before I try to render the texture, there are no errors.
So far, I know that the error means I'm trying to use a "bad" pointer, however I can't seem to find any bad pointers in my code.
This is what my sprite class looks like :
Sprite.h
#pragma once#include "Vector2.h"
#include "Window.h"
#include "Errors.h"
#include <iostream>
#include <SDL\SDL.h>
#include <string>
class Sprite
{
public:
Sprite(std::string id, std::string filePath, Vector2 position, Vector2 size);
~Sprite();
void Draw();
private:
SDL_Texture* texture;
SDL_Surface* surface;
int x;
int y;
};
Sprite.cpp
#include "Sprite.h"
Sprite::Sprite(std::string id, std::string filePath, Vector2 position, Vector2 size)
{
surface = SDL_LoadBMP(filePath.c_str());
if (surface == nullptr)
{
Errors::Error("Failed to load image!", __FILE__, __LINE__);
return;
}
x = position.x;
y = position.y;
surface->w = size.x;
surface->h = size.y;
texture = SDL_CreateTextureFromSurface(Window::GetRenderer(), surface);
//SDL_FreeSurface(surface);
//surface = nullptr;
}
Sprite::~Sprite()
{
//SDL_DestroyTexture(texture);
}
void Sprite::Draw()
{
SDL_Rect rect;
rect.x = x;
rect.y = y;
if (SDL_RenderCopy(Window::GetRenderer(), texture, NULL, &rect) < 0)
{
std::cout << SDL_GetError() << std::endl;
return;
}
}
This is what I've tried so far :
- Checking the texture variable value, which is 0xdddddddd, so I'm guessing this is the locations it fails to read.
- Checking my surface, since texture gets it's image from there, it has the same memory address : 0xdddddddd. However, the w/h, flags etc I can't seem to read because : <Unable to read memory>. So this is probably where the error starts. But it doesn't make sense to me, if this is where the error is created, shouldn't SDL_CreateTextureFromSuface() generate a SDL_GetError() since it's trying to use a bad pointer?
- Checking other values such as x and y, which seem to be off entirely, I set them to 10 however when checking them they are both -572662307.
Other notes :
The if statement where I load the bitmap image doesn't seem to run, so it does load the image properly : (code is taken from Sprite.cpp, check above.)
surface = SDL_LoadBMP(filePath.c_str());
if (surface == nullptr)
{ <- This and down never runs.
Errors::Error("Failed to load image!", __FILE__, __LINE__);
return;
}