Class 24 โ Go Internal Memory (Code, Data, Stack, Heap)
๐ง Topics Covered
This class dives deep into how Go programs are structured in memory. Concepts explained include:
- Code Segment: Stores compiled instructions (functions).
- Data Segment: Stores global/static variables (like
var a = 10
). - Stack: Stores local function variables. Each function call creates a new stack frame.
- Heap: Used for dynamically allocated memory (we'll explore this more later).
- Garbage Collector: Runs on the heap. Cleans up memory that's no longer in use.
๐ Code from Class 24
package main
import "fmt"
var a = 10
func add(x, y int) {
z := x + y
fmt.Println(z)
}
func main() {
add(5,4)
add(a,3)
}
func init() {
fmt.Println("Hello")
}
๐ Code Execution Flow & Memory Layout
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Code Segment โ
โ--------------------------------------------โ
โ Functions: init, main, add โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Data Segment โ
โ--------------------------------------------โ
โ Global Variable: a = 10 โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Stack โ
โ----------------------------โ
โ main() Stack Frame โ
โ - Calls add(5, 4) โ
โ - x=5, y=4 โ
โ - z=9 โ
โ - Calls add(10, 3) โ
โ - x=10, y=3 โ
โ - z=13 โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Heap (Unused here) โ
โ (Managed by the Garbage Collector) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ๏ธ Execution Order
init()
is run automatically beforemain()
โ prints:
Hello
main()
runs and calls: -[]add(5, 4)
โ prints:
-[]9
add(a, 3)
โ usesa = 10
โ prints:13
๐ Key Concepts Recap
Concept | Meaning Code Segment | Where all functions live after compilation Data Segment | Stores global variables Stack | Temporary memory for function execution (local vars, params) Heap | For dynamic memory (we didn't use heap explicitly here) Garbage Collector | Automatically manages memory on the heap init() Function | Special function in Go โ runs before main()
๐งผ Garbage Collector Insight: Goโs GC sits on the heap and sweeps unused allocations to keep memory clean. You won't notice it in this small program, but it's your bestie when your app scales.