0

I have an array of pixels that I display to the screen. To do that I use an SDL_Texture object that gets updated using SDL_UpdateTexture like this:

SDL_UpdateTexture(frame_buffer_texture, nullptr, &frame_buffer_pixels, screen_res_x);

In the documentation it says the the third argument is a pointer to an array of pixels however it doesn't specify if the pixels are copied or not.

Is it okay to use a local variable with the pixels that goes out of scope after SDL_UpdateTexutre like this:

void function()
{
    uint32_t pixels[screen_res_x * screen_res_y] = { /* pixel data here */ }
    SDL_UpdateTexture(texture, nullptr, &pixels, screen_res_x);
}

or do I have to allocate memory for the pixels on the stack like this:

void function()
{
    delete pixels; // Delete old pixels

    pixels = new uint32_t[screen_res_x * screen_res_y];
    // Set pixels values here..

    SDL_UpdateTexture(texture, nullptr, pixels, screen_res_x);
}

Not sure if this matters but here is how I render the texture to the screen:

SDL_RenderClear(renderer);

SDL_RenderCopy(renderer, texture, nullptr, nullptr);

SDL_RenderPresent(renderer);

and here is how it is created:

SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STATIC, screen_res_x * screen_res_y)
                                             
Daniel
  • 85
  • 5
  • 2
    They are copied. "Textures" should be stored in video memory (as opposed to "surfaces" stored in RAM), so the data must be copied. – HolyBlackCat Apr 16 '23 at 19:56

1 Answers1

0

What SDL_UpdateTexture does exactly depends on the renderer, but for reference, the OpenGL renderer calls glTexSubImage2D and the software renderer does a memcpy.

do I have to allocate memory for the pixels on the stack like this

new allocates on the heap. An array like uint32_t pixels[screen_res_x * screen_res_y] is allocated on the stack. But to answer your actual question: no, you do not need to keep the pixel data alive after the call to SDL_UpdateTexture, so you do not need to do a dynamic allocation (on the heap).

However, I would add that if you plan on allocating an array of uint32_t the size of your screen, you might want to do a dynamic allocation regardless. Assuming uint32_t is 4 bytes and your screen size is 1920x1080, that's 1920*1080*4 = 8294400 bytes to allocate. A typical stack size can vary from a few KB to a few MB, so you can easily try to allocate more than your stack allows.

Nelfeal
  • 12,593
  • 1
  • 20
  • 39