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?
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.
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.
Memory in the heap will remain allocated until you free is up using the pointer (memory address) that refers to the data block.
No, malloc() will not release the memory when the function terminates.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With