Course contentsShow
← C
Lesson 342 of 1,2195. FunctionsFree lesson

Memory allocation for parameters

Memory allocation for parameters

What you'll learn: Understand how C creates temporary workspaces in memory for function arguments, keeping your original variables safe.

The Office Photocopy Analogy

Imagine you have a master document sitting on your desk. A colleague asks to work on it, but instead of giving them the original paper, you walk to the copy machine, print a duplicate, and hand them the copy. Your colleague can scribble on their page, highlight it, or even shred it, but your master document remains untouched in your drawer.

In C, when you pass a variable to a function, the computer performs this exact "photocopying" process using your RAM.

The Stack Frame

When a function is called, C carves out a tiny, temporary slice of memory called a Stack Frame. Inside this frame, the computer allocates brand-new memory slots for each parameter defined in the function signature.

If you pass an integer variable named x into a function, C doesn't give the function access to x's original memory address. Instead, it looks at the value stored in x, copies that number, and pastes it into the new memory slot created specifically for that function call.

#include <stdio.h>

void modifyValue(int copyOfNum) {
    // This variable exists in a different memory location
    copyOfNum = copyOfNum + 10; 
    printf("Inside function: %d\n", copyOfNum);
}

int main() {
    int originalNum = 5;
    
    // The value '5' is copied into a new memory slot for the function
    modifyValue(originalNum);
    
    // The original memory slot for originalNum is unchanged
    printf("In main: %d\n", originalNum);
    
    return 0;
}

Why This Matters

Because parameters are allocated their own unique space in memory, the function’s internal logic is "sandboxed." Even if the function reassigns a value to copyOfNum, it is only flipping bits in its own temporary workspace. Once the function finishes its job, that temporary memory (the Stack Frame) is wiped clean and reclaimed by the system. The original variable in your main() function stays exactly as you left it because the function never even knew where the original lived.

Key takeaway

Function parameters are distinct memory allocations that hold copies of data, ensuring that changes made inside a function do not affect the original variables.