C
Relocation
Learn relocation and address patching.
What is relocation?
Relocation is the linker patching relative addresses in object files into final addresses. The compiler assigns relative addresses to each function and variable; when the linker combines sections, these addresses shift.
Each address fix-up is recorded in a relocation entry in the object file. This entry says which address to patch and how. After placing all sections, the linker processes each relocation entry and writes the final values to the relevant addresses. This process lets separately compiled files merge into one executable.
How address patching works
While processing relocation entries, the linker computes the final address of each reference's target symbol. For example, a function call call add is turned into a relative address by the compiler; the linker finds the final address of add and patches the call instruction.
Function pointers are the run-time analogue of this mechanism: a function's address is assigned to a pointer, and a call is made through that pointer. The address may not be known at compile time; at run time the call goes through the pointer. This pattern shows relocation logic at the code level.
Exercise Call through a function pointer
Write int add(int a, int b) { return a + b; }. In int main(void) declare int (*op)(int, int) = add;. Call and print with printf("Sonuç: %d\n", op(40, 2)).
Show example solution
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int main(void) {
int (*op)(int, int) = add;
printf("Sonuç: %d\n", op(40, 2));
return 0;
}
Test yourself
-
Match relocation concept
- Relative address
- Compiler gives
- Final address
- Linker gives
- Relocation entry
- Fix-up record
- Symbol table
- Name list
-
Complete the function pointer assignment
int add(int a, int b) { return a + b; }
int (*op)(int,int) = ____;
Show answer
int add(int a, int b) { return a + b; }
int (*op)(int,int) = add;
-
What does relocation patch?
- Type names
- Addresses
- String values
- Comments
Show answer
Addresses — Relocation patches relative addresses into final addresses.
Next lesson: Static and dynamic