从C中的函数返回局部变量[重复]

时间:2022-07-20 23:40:05

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():

当我使用gcc -ansi -pedantic -W -Wall编译它时,编译器会发出foo2()和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.

我认为不允许返回局部变量,但foo1()工作正常,似乎返回指向本地对象的指针和对象本身之间存在巨大差异。

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

有人可以对这个问题有所了解吗?提前致谢!

4 个解决方案

#1


21  

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.

这里的问题是,当你创建局部变量时,它会在堆栈上分配,因此一旦函数完成执行就不可用(这里的实现会有所不同)。最好的方法是使用malloc()来保留非本地内存。这里的危险是你必须释放(free())你使用malloc()分配的所有东西,如果你忘记了,你就会产生内存泄漏。

#2


16  

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

对于foo1(),返回局部变量的副本,而不是局部变量本身。

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


5  

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.

任何变量在内存中都有一些空间。指针引用该空间。当函数调用返回时,局部变量占用的空间被释放,这意味着它可以并且将被重用于其他事物。因此,对该空间的引用将最终指向完全不相关的东西。 C中的数组实现为指针,因此最终应用于它们。并且在函数中声明的常量数组也算作本地数组。

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.

如果要使用超出创建它的函数范围的数组或其他指针,则需要使用malloc为其保留空间。使用malloc保留的空间在通过免费调用显式释放之前不会被重新分配或重用。

#4


0  

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.

是的,您将返回一个数组,它实际上是一个幕后指针,指向存储您已初始化的变量内容的内存位置的地址。所以它警告你,返回这样的结果可能不那么有用,而你真的可能意味着其中一个数组值。

#1


21  

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.

这里的问题是,当你创建局部变量时,它会在堆栈上分配,因此一旦函数完成执行就不可用(这里的实现会有所不同)。最好的方法是使用malloc()来保留非本地内存。这里的危险是你必须释放(free())你使用malloc()分配的所有东西,如果你忘记了,你就会产生内存泄漏。

#2


16  

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

对于foo1(),返回局部变量的副本,而不是局部变量本身。

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


5  

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.

任何变量在内存中都有一些空间。指针引用该空间。当函数调用返回时,局部变量占用的空间被释放,这意味着它可以并且将被重用于其他事物。因此,对该空间的引用将最终指向完全不相关的东西。 C中的数组实现为指针,因此最终应用于它们。并且在函数中声明的常量数组也算作本地数组。

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.

如果要使用超出创建它的函数范围的数组或其他指针,则需要使用malloc为其保留空间。使用malloc保留的空间在通过免费调用显式释放之前不会被重新分配或重用。

#4


0  

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.

是的,您将返回一个数组,它实际上是一个幕后指针,指向存储您已初始化的变量内容的内存位置的地址。所以它警告你,返回这样的结果可能不那么有用,而你真的可能意味着其中一个数组值。