Course contentsShow
← Computer Science
Lesson 1334 of 2,87231. Memory ManagementFree lesson

Relocation and Dynamic Loading

Understand how programs can be loaded at different memory locations and how code adapts to its runtime address.

Relocation and Dynamic Loading

You'll learn how programs adapt to being loaded anywhere in memory and how code can arrive at runtime, not compile time.

The Challenge: Where Will Your Code Run?

When you compile a program, the compiler doesn't know where in physical memory it will eventually live. Your process might start at address 0x1000 today and 0x5000 tomorrow, depending on what else is running. Relocation is the mechanism that makes this flexibility possible.

What is Relocation?

Relocation means adjusting addresses in a program so it can execute correctly regardless of where it's loaded in memory. Think of it like giving someone directions: instead of saying "meet me at GPS coordinates 40.7128° N," you say "meet me 3 blocks north of the library"—relative, not absolute.

There are two main types:

Static relocation happens at load time. The loader knows where the program will sit in memory and patches all addresses once before execution starts.

Dynamic relocation happens continuously during execution using hardware support (like base registers you learned about). The CPU adds the base register value to every address the program generates, translating logical addresses to physical ones on the fly.

Dynamic Loading

Dynamic loading takes this further: not all code needs to be in memory from the start. Modules or libraries can be loaded only when needed—like streaming a video instead of downloading it all first. This saves memory and allows programs to grow beyond physical RAM limits by loading pieces on demand.

When a function in a dynamically loaded module is called for the first time, a stub loads it into memory, updates pointers, then jumps to it.

Key Takeaway: Relocation lets programs run at any memory address by adjusting references either at load time (static) or during execution (dynamic), while dynamic loading defers bringing code into memory until it's actually needed.