Stack and Heap memory in golang

Quick tech learn
2 min readSep 7, 2023

--

In Go (also known as Golang), variables are stored in either the stack or the heap, depending on their characteristics.

1. Stack Memory:

  • Stack memory is used for storing local variables and function call data, including function parameters and return addresses.
  • Variables allocated on the stack have a fixed size and are typically short-lived, as they are deallocated automatically when the function that created them exits.
  • Go automatically manages the stack memory, and you don’t have to worry about memory deallocation for stack-based variables.
  • Basic data types, such as integers, floats, and pointers, are often stored on the stack.
  • Variables with a known, fixed size at compile time are generally allocated on the stack.

2. Heap Memory:

  • Heap memory is used for dynamically allocated data that doesn’t have a fixed or known size at compile time.
  • Variables allocated on the heap are typically longer-lived, and their memory must be explicitly managed by the programmer (e.g., through garbage collection).
  • Complex data structures like slices, maps, and structs containing slices or maps often use heap memory.
  • Strings in Go are implemented as read-only byte slices (immutable), and the actual string data is typically stored in the heap.
  • When you use the make function to create slices, maps, or channels, they are allocated on the heap.

In Go, you don’t have direct control over whether a variable is stored in the stack or heap. The Go runtime and compiler make these decisions based on the variable’s scope, lifetime, and size. Stack memory is generally more efficient for small, short-lived variables, while heap memory is used for larger, dynamically allocated data structures.

Go’s automatic memory management, including garbage collection for heap-allocated objects, simplifies memory management for developers and helps prevent common memory-related bugs like memory leaks and use-after-free errors.

--

--

Quick tech learn

Blogs are written by a fullstack developer with experience in tech stack like golang, react, SQL, mongoDB and cloud services like AWS