returning a local variable from function in C

Mark picture Mark · Jan 28, 2011 · Viewed 51k times · Source
#include <stdio.h>

int foo1(void)
{
    int p;
    p = 99;
    return p;
}

char *foo2(void)
{
    char buffer[] = "test_123";
    return buffer;
}

int *foo3(void)
{
    int t[3] = {1,2,3};
    return t;
}

int main(void)
{
    int *p;
    char *s;

    printf("foo1: %d\n", foo1());
    printf("foo2: %s\n", foo2());
    printf("foo3: %d, %d, %d\n", p[0], p[1], p[2]);
    return 0;
}

When I compile this with gcc -ansi -pedantic -W -Wall the compiler issues warning messages for foo2() and foo3():

warning: function returns address of local variable

I thought it is not allowed to return a local variable, but foo1() works fine and it seems there is a huge difference between returning pointer to a local object and the object itself.

Could anybody shed some light on this issue? Thanks in advance!

Answer

kelloti picture kelloti · Jan 28, 2011

The issue here is that when you create the local variable it is allocated on the stack and is therefore unavailable once the function finishes execution (implementation varies here). The preferable way would be to use malloc() to reserve non-local memory. the danger here is that you have to deallocate (free()) everything you allocated using malloc(), and if you forget, you create a memory leak.