0

What is the advantage of declaring variable in stack

Since you can use new variables from the heap, which you can keep juste as with those from the stack, but also can erase etc. To release memory. Anyhow, you can do both and thus whatever you want with variable from the heap, so what is the advantage in using variable from the stack ? Or maybe I understood something wrong, possible too since I'm only at the "functions" chapter ^^

5th Feb 2019, 10:11 PM
Etienne Wiest
Etienne Wiest - avatar
7 Respuestas
0
When a function is finished, it frees the memory used to store local variables on the stack (so this memory can be used again). Learn more about stack, you'll understand what I mean...
6th Feb 2019, 1:21 PM
Théophile
Théophile - avatar
+ 2
Using the stack is good for small variables or for pointers on objects that are declared in the heap. Don't forget the size of the stack is limited, while the size of the heap can change. In functions, local variables are stored on the stack and are deleted at return statement (see stack pointer in assembly, you will easily understand).
5th Feb 2019, 10:35 PM
Théophile
Théophile - avatar
0
It doesn't completely answer my question as I already understood those points. I mean, precisely, the size of the heap can adapt where the size of the slack is limited. So why declare even small variables in the slack when I could just use pointers and go with variables in the heap with the same efficiency in the heap, but with more flexibility on the memory ?
6th Feb 2019, 6:44 AM
Etienne Wiest
Etienne Wiest - avatar
0
Using stack, you're sure that there is no memory leaking.
6th Feb 2019, 1:00 PM
Théophile
Théophile - avatar
0
From what I understood, memory leaking is about having a memory space used up for nothing because it's attributed to a variable you do not need anymore... But if you have the variable in the slack, then you cannot free the memory space anyhow... Isn't that like a memory leak ? (Sorry if those questions seems dumb, I really try to wrap my head around how the memory works)
6th Feb 2019, 1:18 PM
Etienne Wiest
Etienne Wiest - avatar
0
Ok, I'll do that, and come back if I don't ;) thx !
6th Feb 2019, 1:23 PM
Etienne Wiest
Etienne Wiest - avatar
0
Here is a "picture" Before a function call : stack address value 0x00 int a //local variable a 0x01 0x02 After function call address value 0x00 int a 0x01 return address 0x02 int b //local variable b After return statment address value 0x00 int a 0x01 0x02
6th Feb 2019, 1:42 PM
Théophile
Théophile - avatar