Returning static local variables as references

Byzantian picture Byzantian · Nov 16, 2012 · Viewed 7k times · Source

What happens to a static variable when returned as a reference and passed as a pointer directly to another function? Obviously, the variable persists after the function returns, but something about this whole concept just bothers me. At which point is the memory on the data-sequent, occupied by the static variable, freed? Does the runtime magically notice when I no longer need it, like some kind of garbage collection?

To give an example:

SDL_Rect* XSDL_RectConstr(int x, int y, int w, int h)
{
    static SDL_Rect rect;
    rect.x = x;
    rect.y = y;
    rect.w = w;
    rect.h = h;

    return ▭
}

void mainLoop()
{
    while(isRunning)
    {
        pollEvents();
        SDL_BlitSurface(someSurface, XSDL_RectConstr(0, 0, 100, 100), screen, NULL);
        SDL_Flip(screen);
    }
}

What happens to rect after SDL_BlitSurface() returns? I can't see when it would be freed. Wouldn't this be some kind of memory leak then?

Answer

hate-engine picture hate-engine · Nov 16, 2012

At which point is the memory on the data-sequent, occupied by the static variable, freed? Does the runtime magically notice when I no longer need it, like some kind of garbage collection?

It would be freed at program exit, not sooner. Also, it's guaranteed that destructors would be called.