Byzantian
Byzantian

Reputation: 3348

Returning static local variables as references

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?

Upvotes: 16

Views: 10935

Answers (3)

john
john

Reputation: 87959

There's no memory leak, but it's a really, really bad idea. Suppose you wrote some code like this

SDL_someFunction(
    XSDL_RectConstr(0, 0, 100, 100), 
    XSDL_RectConstr(20, 20, 30, 30)
);

Because you have only one static rectangle, SDL_someFunction is not going to get the different rectangles that it looks like it's going to get. Instead you will get the same rectangle twice.

Upvotes: 6

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726509

rect will not be freed upon return from SDL_BlitSurface, but it would not be a memory leak either: it's in the static storage, so there is nothing to "leak". The object will stay in memory for as long as your program is running.

The biggest downside to this happens when you start multithreading: your static variable runs a risk of being modified from multiple threads concurrently, which is something that you would rather avoid.

Destructors for initialized objects of static storage duration (declared at block scope or at namespace scope) are called as a result of returning from main and as a result of calling exit.

Upvotes: 6

hate-engine
hate-engine

Reputation: 2350

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.

Upvotes: 14

Related Questions