C
PY

C to Python

10 lessons

Progress0%
1Variables & Types2Functions3Arrays → Lists4Structs → Classes & Dicts5Memory Management6String Handling7File I/O8Object-Oriented Programming9Exceptions and Context Managers10Standard Library and Tools
All Mirror Courses
C
PY
Memory Management
MirrorLesson 5 of 10
Lesson 5

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.

Mirror Card
C
From C:

In C, you're familiar with how memory is allocated and freed.

PY
In Python:

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:

PY
Python 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:

C
C (What you know)
#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);
Mirror Card
C
From C:

You may be used to different syntax or behavior.

PY
In Python:

C: manual malloc/free — Python: automatic garbage collection

Mirror Card
C
From C:

You may be used to different syntax or behavior.

PY
In Python:

C memory leaks are your problem; Python's GC handles reclamation

Mirror Card
C
From C:

You may be used to different syntax or behavior.

PY
In Python:

C segfaults on bad pointers; Python raises exceptions instead

Mirror Card
C
From C:

You may be used to different syntax or behavior.

PY
In Python:

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.

C
C
int *arr = malloc(10 * sizeof(int));
// ... use arr ...
free(arr);
PY
Python
arr = [0] * 10  # allocated automatically
# ... use arr ...
# freed automatically

2. Reference Counting

Python tracks how many variables reference each object. When the count drops to zero, the memory is freed immediately.

Common Pitfall
Circular references can prevent immediate collection — Python's cyclic GC handles these periodically.

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.

PY
Python
import numpy as np
arr = np.zeros(1_000_000, dtype=np.int32)  # contiguous C memory

Common 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
Common Pitfall
Don't assume Python works exactly like C. While the concepts may be similar, the syntax and behavior can differ significantly.

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
Rule of Thumb
The best way to learn is by doing. Try rewriting some of your C code in Python to practice these concepts.
PreviousNext