What are stack and heap?
sobes.tech AI
Answer from AI
Stack and Heap are two memory areas used by a program during execution.
-
Stack is a memory area for storing local variables, function parameters, and return addresses. It operates on a LIFO (last in, first out) principle. The stack size is usually limited and managed automatically. In Go, the stack is used to store primitive values and pointers, as well as to manage function calls.
-
Heap is a memory area for dynamically allocating objects, and its size can change during runtime. In Go, objects that live longer than the function call or are too large for the stack are placed on the heap. Memory management in the heap is handled by a garbage collector.
Example:
func foo() {
x := 10 // x is stored on the stack
p := new(int) // allocation on the heap
*p = 20
}
Here, x is a local variable on the stack, and p is a pointer to an area on the heap.
Thus, the stack is a fast, size-limited storage for temporary data, while the heap is a more flexible area for dynamically created objects.