CodeBlanks Logo Icon CodeBlanks

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.

Practice 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)).

Starter code

main.c
#include <stdio.h>

// add fonksiyonu yaz
// işlev göstergesi tanımla
// çağır ve yazdır

Sample solution

main.c
#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;
}

Expected output

Sonuç: 42

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match relocation concept

Term Meaning
Relative address Compiler gives
Final address Linker gives
Relocation entry Fix-up record
Symbol table Name list

2 Complete the function pointer assignment

Question
int add(int a, int b) { return a + b; }
int (*op)(int,int) = ____;
Answer
int add(int a, int b) { return a + b; }
int (*op)(int,int) = add;

Explanation: The function name gives its address; it can be assigned to a pointer.

3 What does relocation patch?

  • Type names
  • Addresses Correct answer
  • String values
  • Comments

Explanation: Relocation patches relative addresses into final addresses.

All lessons in Expert