Skip to main content
InterviewHubPRO
Section Overview
Q4

Question 4 of 50

Part 1: Go Language Core, Memory & Runtime Internals (1 - 15)

8%
Golang & Concurrency (50 Qs)•Part 1: Go Language Core, Memory & Runtime Internals (1 - 15)

Explain the Go Memory Model: Stack vs. Heap Allocation and Escape Analysis.

senior LevelCode ExampleMemory ManagementGolangData Structures

In Simple Words: In C/C++, the developer explicitly manages malloc/free. In Go, the compiler decides whether a variable lives on the Stack or Heap via Escape Analysis:

  • Stack: Ultra-fast allocation (pointer bump) and deallocation when the function returns. Zero GC overhead.
  • Heap: Used when a variable outlives the stack frame of the function that created it (e.g. returning a pointer to a local variable), or when interface boxing occurs. Heap variables must be tracked and collected by the Garbage Collector.
go
// Escape Analysis Example:
func allocateStack() int {
	x := 42
	return x // Allocated on STACK (value copied)
}

func allocateHeap() *int {
	x := 42
	return &x // ESCAPES to HEAP (pointer outlives function scope)
}
// Inspect with: go build -gcflags="-m"