Hi, how can I know if I should use the heap or the stack when I am programming in C ?? Thanks | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Hi, how can I know if I should use the heap or the stack when I am programming in C ?? Thanks

4th Feb 2020, 5:26 PM
Carlos Caminero
2 Answers
+ 2
Stack memory is used for local variables and methods which are generally temporary and may not be used throughout the program. It follows LIFO so when ever you create a variable or make a call to a method, they are pushed on to the stack but as soon as they go out of scope, they are popped out. Stack has very less memory but the memory management is automatic because it is taken care by the CPU.
4th Feb 2020, 5:53 PM
Avinesh
Avinesh - avatar
+ 2
Heap on the other side is generally used when you have a large amount of data to store. The memory has to be managed by the programmer because for every chunk of memory you use, you have to free it at the end of the program to avoid memory leaks because the heap memory is not automatically managed. It's up to you to draw conclusions from the above statements but I would recommend you to make use of stack as long as you can and use heap only if you have to deal with large storage space.
4th Feb 2020, 5:58 PM
Avinesh
Avinesh - avatar