+ 2

Static and dynamic memory

Please explain what is the stack and the heap? Why do we have a difference in memory (static and dynamic memory )?

10th Jun 2019, 3:07 AM
Chetan Satpute
Chetan Satpute - avatar
3 odpowiedzi
+ 1
The stack is used for static memory. Inside a function, when you declare a variable, it is stored on the stack. When the function call is finished, then all the stack is freed. When a function is called, here is the stack Adress VALUE 0x07 return adress 0x06 int a = 10 0x05 int b = 100 ... The integers are variables declared in the function After this function call Adress VALUE 0x07 0 0x06 0 You see, the stack allocated for the function call is freed, so the variables you declared there (a and b) doesn't exist anymore. (in fact, you can always access the value, but it is hard to explain : Learn assembly)
10th Jun 2019, 8:17 AM
Théophile
Théophile - avatar
+ 1
The heap isn't used like the stack. You access the heap only through pointers. An example, in c++ int *a = new int ; *a = 10 ; Here, the value pointed by a isn't stored on the stack but on the heap. But the pointer, a, is declared on the stack. That means that after a function call, the pointer a will be destroyed on the stack, but the value pointed by a will survive on the heap : that are memory leaks. Another difference between stack and heap is that the heap is very very large, and that memory allocated on it is in fact allocated by the os, not by the program : you can't know by advance where memory will be allocated. In assembly, you work directly with stack thanks to esp and ebp register, so you can know by advance where memory will be allocated.
10th Jun 2019, 8:29 AM
Théophile
Théophile - avatar
+ 1
Watch mycodeschool channel videos on YouTube you'll be perfectly well known about stack and heap in C programs
14th Jun 2019, 6:28 PM
Zuhail
Zuhail - avatar