[SDL 3.x] SDL_CreateSurface and SDL_DestroySurface = SIGSEV

Why does it crash when I try to unlock the Surface with SDL Destroy Surface(...)?

#include <SDL3/SDL.h>

int main(int argc, char *argv[])
{
    SDL_Init(SDL_INIT_VIDEO);

    SDL_Surface *SrcSurface = SDL_CreateSurface(1, 1, SDL_PIXELFORMAT_RGBA32);

    unsigned char pixels[] = {0xFF, 0x00, 0x00, 0x00};
    SrcSurface->pixels = &pixels;

    SDL_Log("Destroy SrcSurface");
    SDL_DestroySurface(SrcSurface);  // Crash
    SDL_Log("Destroy SrcSurface");

    SDL_Quit();

    return 0;
}

SDL_DestroySurface will try to free this pointer. You should copy memory with memcpy.

1 Like

Thanks
I even solved it more elegantly with SDL_memcpy.
I suspect that I even had a memory leak with the direct assignment. The pixels that were created with SDL_CreateSurface(...) were then somewhere in the memory grave.

SDL_memcpy(SrcSurface->pixels, &pixels, sizeof(pixels));