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!

0

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

2/4/2020 5:26:31 PM

Carlos Caminero

2 Answers

New Answer

+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.

+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.