This topic sounds pretty elementary, but I did not know the difference a week ago. Just explain it here as a record. You may also want to have a look at this page.
Memory can be allocated on the heap or on the stack. When a program calls malloc() family, the memory will be allocated on the heap. When you define a variable or an array or call alloca(), the memory will be allocated on the stack. The data on the stack are separated by frames. Each time a open-brace is met, a scope is initiated and a frame which contains the data in the scope will be pushed on the stack; each time a close-brace is met, the scope is over and the frame will be removed. To this end, memory allocated on the stack is transcient. Pointers pointed to such memory become invalid when the scope is over.
Allocation on the stack is more convenient and cheaper, but the maximum stack size is limited. It may cause stack overflow if your program allocates large memory on the stack. In addition, allocating large arrays on the stack may fool valgrind (see here). Usually, large arrays should be allocated on the heap.
Leave a Reply