returning a local variable from function in C [dup

2018-12-31 02:04发布

This question already has an answer here:

#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!

4条回答
泪湿衣
2楼-- · 2018-12-31 02:42

For foo1(), you return a copy of the local variable, not the local variable itself.

For the other functions, you return a copy of a pointer to a local variable. However, that local variable is deallocated when the function finishes, so you end up with nasty issues if you try to reference it afterwards.

查看更多
宁负流年不负卿
3楼-- · 2018-12-31 02:42

Any variable has some space in the memory. A pointer references that space. The space that local variables occupies is deallocated when the function call returns, meaning that it can and will be reused for other things. As a consequence, references to that space are going to wind up pointing to something completely unrelated. Arrays in C are implemented as pointers, so this winds up applying to them. And constant arrays declared in a function also count as being local.

If you want to use an array or other pointer beyond the scope of the function in which it is created, you need to use malloc to reserve the space for it. Space reserved using malloc will not be reallocated or reused until it is explicitly released by calling free.

查看更多
何处买醉
4楼-- · 2018-12-31 03:03

Yes you are returning an array, which is actually a pointer behind the scenes, to the address of the memory location where the contents of the variable you've initialised is stored. So it's warning you that it might not be quite as useful to return such a result, when you might really mean one of the array values instead.

查看更多
时光乱了年华
5楼-- · 2018-12-31 03:06

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.

查看更多
登录 后发表回答