Search code examples
c++visual-studiosdl-2

How to fix "Exception thrown: read access violation. **Surface** was nullptr. occurred" in SDL2 C++


Im trying to learn SDL2 with c++,

and every time I try to fill a surface i get this error, searched on the internet for a solution and haven`t found one yet:

SDL_Surface* Surface = NULL;
SDL_FillRect(Surface, NULL, SDL_MapRGB(Surface->format, 0, 255, 0));

every time I run this, it doesn't show an error but it does break the code and shows an X and a little box with the text "Exception thrown: read access violation. Surface was nullptr." near the FillRect line. I can click "Copy Details" and then it copies "Exception thrown: read access violation. ** Surface ** was nullptr. occurred"


Solution

  • You need to use something like

    SDL_CreateRGBSurface
    

    instead for NULL. Because you cant write to something that doesn't exist in memory.