Search code examples
c++pointersmemorysdlheap-memory

SDL why create textures on the heap instead of stack


So I've been reading over lazyfoos SDL2 tutorials and I was just curious how come all of the SDL_Surface/SDL_textures etc are created on the heap? I realize SDL itself was written in C and the functions accept/return pointers, but why not create the surface on the stack and pass a reference of it to the function? (Or dereference it when assigning)

Hopefully I've been clear. Here's a code snippet to further try to explain:

why this:

void pointer()
{
    SDL_Surface *windowsurface;
    SDL_Surface *surface = SDL_LoadBMP("asdf.bmp");
    SDL_BlitSurface(surface, 0, windowsurface, 0);
}

instead of this:

void stack()
{
    SDL_Surface windowsurface;
    SDL_Surface surface = *(SDL_LoadBMP("asdf.bmp"));
    SDL_Blit(&surface, 0, &windowsurface, 0);
}

If the latter is indeed possible, would you still need to call SDL_FreeSurface? If so this would ensure you won't leak any memory so I don't quite see the benefit of the former.

Hopefully this all makes sense, I'm still a rookie when it comes to SDL


Solution

  • There are a whole bunch of reasons for this but I will focus on just one. Specifically, in C++ there is no portable way to create an object of size unknown at compile time on the stack.

    This is a substantial problem as a texture is of unknown size to the compiler as it does not know how large the data loaded into it will be. In C this can be somewhat helped with the use of VLAs however these are still inadvisable for large objects due to small stack sizes available on many OSes.

    In addition to all this the texture may be implemented in GPU memory rather than main memory. This absolutely cannot be on the stack and must be managed by the graphics routines in whatever system is being used. These graphics systems often just provide an opaque pointer to a texture in GPU memory which can be freed or managed with provided routines.

    Now you could argue that the handle structure could live in the stack at least but in reality this provides minimal savings as the vast majority of reads and writes will be to the texture itself and not to the handle object so optimising that has little value.