Sobes.tech
Senior

What is a stack and what is a heap?

sobes.tech AI

Answer from AI

Stack and heap are two areas of memory with different purposes and management.

  • Stack is a memory area for storing local variables, function parameters, and return addresses. Stack management is automatic: a new frame is allocated when a function is called, and freed when it exits. The stack is usually limited in size and operates very quickly.

  • Heap is a memory area for dynamic allocation, where objects live longer than the function call. Heap management requires explicit allocation and deallocation of memory (in Go — garbage collection). The heap is larger in size but operations with it are slower.

In Go, the stack is used for local variables and calls, while the heap is for objects with dynamic lifetimes, for example, allocated via new or make.

Example:

func foo() {
    x := 10 // on the stack
    p := new(int) // on the heap
    *p = 20
}