Memory Management
How memory is allocated and freed
Introduction
In this lesson, you'll learn about memory management in Python. Coming from C, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In C, you're familiar with how memory is allocated and freed.
Python has its own approach to how memory is allocated and freed, which we'll explore step by step.
The Python Way
Let's see how Python handles this concept. Here's a typical example:
# No manual memory management!
# Python uses garbage collection (reference counting + GC)
# Lists grow automatically
arr = []
arr.append(1)
arr.append(2)
arr.extend(range(20)) # no realloc needed
# Strings are immutable objects — no strdup needed
s = "hello"
s2 = s + " world" # creates a new string
# Memory is freed automatically when objects go out of scope
def process():
big_data = [0] * 1_000_000 # allocated
# ... use big_data ...
# freed automatically when function returns
# For large data, use array module or numpy for efficiency
import array
nums = array.array('i', [1, 2, 3, 4, 5])Comparing to C
Here's how you might have written similar code in C:
#include <stdlib.h>
#include <string.h>
/* Stack allocation — automatic */
int x = 42; /* freed when function returns */
/* Heap allocation — manual */
int *arr = malloc(10 * sizeof(int));
if (!arr) { /* handle allocation failure */ }
arr[0] = 1;
arr[1] = 2;
/* Resize */
arr = realloc(arr, 20 * sizeof(int));
/* Must free to avoid memory leak */
free(arr);
arr = NULL; /* avoid dangling pointer */
/* Dynamic string */
char *s = strdup("hello");
free(s);You may be used to different syntax or behavior.
C: manual malloc/free — Python: automatic garbage collection
You may be used to different syntax or behavior.
C memory leaks are your problem; Python's GC handles reclamation
You may be used to different syntax or behavior.
C segfaults on bad pointers; Python raises exceptions instead
You may be used to different syntax or behavior.
Python lists are always heap-allocated; no stack arrays
Step-by-Step Breakdown
1. No malloc/free
Python's garbage collector automatically frees memory when objects are no longer referenced. You never call malloc or free.
int *arr = malloc(10 * sizeof(int));
// ... use arr ...
free(arr);arr = [0] * 10 # allocated automatically
# ... use arr ...
# freed automatically2. Reference Counting
Python tracks how many variables reference each object. When the count drops to zero, the memory is freed immediately.
3. Efficiency for Large Data
When you need C-like memory efficiency (e.g., large numeric arrays), use the array module or numpy instead of Python lists.
import numpy as np
arr = np.zeros(1_000_000, dtype=np.int32) # contiguous C memoryCommon Mistakes
When coming from C, developers often make these mistakes:
- C: manual malloc/free — Python: automatic garbage collection
- C memory leaks are your problem; Python's GC handles reclamation
- C segfaults on bad pointers; Python raises exceptions instead
Key Takeaways
- No malloc/free in Python — use lists and let GC handle memory
- Python raises exceptions instead of causing segfaults
- Use numpy for memory-efficient numeric arrays
- Circular references handled by Python's cyclic GC