Course contentsShow
← C
Lesson 558 of 1,2198. Memory ManagementFree lesson

Returning addresses of local variables

Returning addresses of local variables

What you'll learn: Why returning a pointer to a variable created inside a function causes your program to crash or behave unpredictably.

The Disappearing House

Imagine you are staying at a hotel. You write your room number, "Suite 402," on a piece of paper and give it to a friend so they can visit you later. However, the moment you check out, the hotel management immediately renovates Suite 402, tears down the walls, or lets a stranger move in.

If your friend tries to enter Suite 402 using your note, they are walking into a room that no longer belongs to you. In C, this is exactly what happens when you return the address of a local variable.

Local Scope and the Stack

When a function runs, it carves out a tiny slice of memory for its own use, called a "stack frame." Any variables you declare inside that function live in that slice. The moment the function finishes (hits the return statement), that slice of memory is marked as "available" for the rest of the computer to use. The variables inside it effectively cease to exist.

If you return the memory address (a pointer) of one of those local variables, the pointer itself makes it back to the caller, but the data it points to is now "garbage."

A Recipe for Disaster

Look at this common mistake:

#include <stdio.h>

int* get_number_pointer() {
    int local_num = 42;  // Created on the stack
    return &local_num;   // WARNING: local_num dies after this line!
}

int main() {
    int* ptr = get_number_pointer();
    
    // This is dangerous! The memory ptr points to is no longer reserved.
    printf("The value is: %d\n", *ptr); 
    
    return 0;
}

In this code, ptr is a dangling pointer. It holds a valid memory address, but that address is no longer "rented" by your variable. If you try to print *ptr, you might get 42, or you might get a random number, or your program might simply crash (a Segmentation Fault). The behavior is "undefined," which is a programmer's way of saying "anything bad could happen."

How to fix it

If you need a function to provide a pointer to data, that data must live somewhere more permanent. Usually, this means either passing a pointer into the function from the outside or using dynamic memory (like malloc), which stays alive until you manually delete it.

Key takeaway

Never return the address of a local variable, as the memory it occupies is reclaimed the moment the function ends.