Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 876
Byzantian Avatar asked Nov 16 '12 21:11

Byzantian


3 Answers

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.

like image 131
hate-engine Avatar answered Oct 24 '22 07:10

hate-engine


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.

like image 40
john Avatar answered Oct 24 '22 05:10

john


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.

like image 38
Sergey Kalinichenko Avatar answered Oct 24 '22 06:10

Sergey Kalinichenko