Memory allocated with alloca gets freed at end of function or at end of scope?
Asked Answered
S

3

12

If I have a function like this:

void bla(int size) {
    while(b){
        char tmp[size];
        ......
    }
}

tmp gets freed at each iteration of the while loop, right?

If I write this function:

void bla(int size) {
    while(b){
        char* tmp = alloca(size);
        ......
    }
}

tmp gets freed at end of scope or at end of function?

Sadoc answered 23/3, 2011 at 15:23 Comment(0)
A
10

It will be freed at end of function, but since you call alloca() inside the loop you'll likely get stack overflow. If size doesn't change within the function you should call alloca() before the loop.

Archipelago answered 23/3, 2011 at 15:25 Comment(1)
Or use a VLA instead of alloca. In fact this is the main difference between VLAs and alloca - the scope of the automatic array is block scope with VLA and function scope with alloca.Mechanize
S
3

alloca allocates on the stack and has no knowledge about scopes, so it gets freed after leaving the stack frame (= after leaving the function).

Stated answered 23/3, 2011 at 15:24 Comment(0)
A
3

Memory allocated with alloca() is deallocated when the function exits. See for instance the manual page for more information.

Regarding the former case, of just an auto-variable in the scope, I'm not sure how you would define that it gets "freed". You can't reference it outside of the scope that defines it, and if it had an initializer it would get re-initialized on each iteration.

Auberge answered 23/3, 2011 at 15:25 Comment(1)
it gets freed in a very exact sense. The standard distinguishes scope and lifetime of a variable. For VLA it ensures that the end of its lifetime is identical to the end of the execution of its scope. So the memory it occupies is effectively freed. The size expression is computed at each iteration and the lifetime only starts then. BTW, VLA are not allowed to have initializers.Merriweather

© 2022 - 2024 — McMap. All rights reserved.