Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 964
Damian Avatar asked Mar 23 '11 15:03

Damian


People also ask

Does Alloca need to be freed?

The alloca() function allocates size bytes of space in the stack frame of the caller. This temporary space is automatically freed when the function that called alloca() returns to its caller.

Is memory freed when function returns?

The memory does NOT get freed with you “return” from a function. However, it IS (effectively) freed when the program itself (Windows EXE or equivalent on *nix) exits.

When can the memory allocated to food be released from the heap?

Memory in the heap will remain allocated until you free is up using the pointer (memory address) that refers to the data block.

Does malloc automatically free memory?

No, malloc() will not release the memory when the function terminates.

Does C automatically deallocate memory?

No it doesn't clear. The malloc function will request a block of memory from the heap . You have to pass the pointer returned form malloc to the free function when is no longer needed which deallocates the memory so that it can be used for other purposes.


1 Answers

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.

like image 186
sharptooth Avatar answered Oct 05 '22 22:10

sharptooth