csdl-2sdl-image

This function cause the window to be blank then crashes


I'm trying to find why thus code doesn't work, and after some testing I found that the function submitSprite has the cause of the crash in it, but I don't know how to fix it

#include "renderer.h"

Renderer newRenderer(SDL_Window* window)
{
    Renderer renderer;
    renderer.renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);

    return renderer;
}

void destroyRenderer(Renderer renderer)
{
    SDL_DestroyRenderer(renderer.renderer);
}

void submitSprite(Renderer renderer, Sprite sprite)
{
    SDL_Rect* rect;
    rect->x=sprite.x;
    rect->y=sprite.y;
    rect->w=sprite.w;
    rect->h=sprite.h;

    SDL_RenderCopy(renderer.renderer, sprite.texture, NULL, rect);
}

void render(Renderer renderer)
{
    SDL_RenderPresent(renderer.renderer);
    SDL_RenderClear(renderer.renderer);
}

renderer.renderer is an SDL_Renderer*


Solution

  • void submitSprite(Renderer renderer, Sprite sprite)
    {
        SDL_Rect* rect;
        rect->x=sprite.x;
        rect->y=sprite.y;
        rect->w=sprite.w;
        rect->h=sprite.h;
    
        SDL_RenderCopy(renderer.renderer, sprite.texture, NULL, rect);
    }
    

    Here you access an pointer which was never initialized. So either use a local variable, or a allocate (and free) memory for it.

    i.e.:

    void submitSprite(Renderer renderer, Sprite sprite)
    {
        SDL_Rect rect;
        rect.x=sprite.x;
        rect.y=sprite.y;
        rect.w=sprite.w;
        rect.h=sprite.h;
    
        SDL_RenderCopy(renderer.renderer, sprite.texture, NULL, &rect);
    }