Search code examples
cvariablespointersparameterslocal

Why is it bad practice to return a pointer to a local variable or parameter?


I found this question on my study guide, and I am not sure why it would be bad to return a pointer to a local variable/parameter. Any ideas?


Solution

  • It's not so much a "bad practice" (implying that it might cause problems) as much as it is a practice that will absolutely cause undefined behavior. It's like dereferencing a null pointer: don't do it and expect your program to behave within the limits of logic.

    Explanation:

    When a local variable (including a parameter) is declared, it is given automatic storage, meaning that the compiler takes care of allocating memory for the variable and then deallocating that memory without any effort on the part of the programmer.

    void foo(int bar)
    {
        int baz;
    } //baz and bar dissappear here
    

    When the variables' lifetime ends (such as when the function returns), the compiler fulfills its promise and all automatic variables that were local to the function are destroyed. This means that any pointers to those variables now point to garbage memory that the program considers "free" to do whatever it wants with.

    When returning a value, this isn't a problem: the program finds a new place to put the value.

    int foo(int bar)
    {
        int baz = 6;
        return baz + bar; //baz + bar copied to new memory location outside of foo
    } //baz and bar disapear
    

    When you return a pointer, the value of pointer is copied as normal. However, the pointer still points to the same location which is now garbage:

    int* foo(int bar)
    {
        int baz = 6;
        baz += bar;
        return &baz; //(&baz) copied to new memory location outside of foo
    } //baz and bar disapear! &baz is now garbage memory!
    

    Accessing this memory is undefined behavior, so your program will almost certainly misbehave in some way or another. For instance, I once fell victim to this exact problem, and while my program did not crash or terminate, my variables began degrading into garbage values as the compiler overwrote the "free" memory.