Go Memory Allocation
Zaffere
Posted on January 18, 2023
What is memory allocation
Memory allocation is the process of how programming languages store or keep track of in-memory data like variables, arguments or any other data in your program’s runtime.
There are two places where the runtime keeps track of memory; Heap
& Stack
Heap
A Heap
(same name as the data structure but not related at all) is a portion of physical memory on your machine where global variables, arguments or any data used by the runtime is stored. Heaps
are generally shared by the entire program meaning that all stacks
have access to data stored in the heap
.
Data in the heap
stays in the heap
until it is freed or your program terminates.
Go has aGarbage Collector
and it is responsible for freeing up unused data in the heap
automatically for us (we can manipulate this behaviour with the runtime
package)
Stack
Stack
is a short lived memory space to store data that is local to a function or a thread (goroutine
).
Memory in the stack are removed once the function or goroutine
returns/terminates.
Any new memory that is created inside of a stack
that is passed and used outside of the stack (*****************passed up the stack*****************) is said to have escaped to the heap
. This is when the memory is “transferred” over to the heap
from the stack.
Passing down the stack
Passing down the stack
refers to passing an address of a variable
instead of the value of the variable itself down to a function.
Example of Passing down the stack
package main
func main() {
num := 2
add(&num)
}
func add(i int) {
result := *i + 10
return result
}
Passing up the stack
Passing up the stack
refers to passing an address of a variable
instead of the value of the variable itself up/outside the function.
Example of passing up the stack:
package main
func main() {
num := getNum()
}
func getNum() int {
number := 7
// This causes the variable number to be moved to the heap
return &number
}
Posted on January 18, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.