0
What is Heap and Stack?
What do they respectively store?
2 odpowiedzi
+ 2
When you program in C or C++, the stack and the heap are two separate data structures used to store variables.
The stack is where you typically put your variables. It's fast, it's simple, and it's static, meaning that the amount of stack memory you use doesn't change throughout the program's run.
The heap is different. Heap memory is dynamic, meaning that you can change the amount of memory you're using at will, but it's slower and can be unstable if you're not careful. It's also something you have to manage yourself, as opposed to stack memory, which is automatically managed for you.
+ 2
One of the main parts of C is that you can manipulate memory manually.
There exist two catagories of memory involved in a program: the Stack and the Heap
The stack has a predetermined amount of memory and going over this limit results in a STACK OVERFLOW. This happens when you get infinite loops among other things. Each thread in a program has its own stack, which is reabsorbed when the thread terminates.
Dynamic memory manipulation falls under the jurisdiction of the heap, which is the same for all threads of a program and has no limit to its size as it "negotiates" with the OS for more. The way you access the heap in C is through pointers(and arrays which are a kind of constant pointer) Whereas the stack is susceptible to stack overflows, the heap is susceptible to fragmentation when there is enough memory to support storing something on the heap but it doesn't exist in a continuous way and is spread out all over the heap(like fragments of broken glass. Things in the heap exist in a global sense in the program since it is shared with all threads, and also, for the same reason is slower since it can only be accessed/changed by one thread at a time.
Using the stack is simpler and faster to deal with and the heap, as a consequence of how it is accessed/manipulated is slower and more complex since the programmer has to be careful to free up heap memory when it is finished to avoid memory overflows.
This post may be more than you asked for, but all of the information is useful and goes together and by no means am I saying not to use the heap, simply to be cognizant while using it.