C语言 从 C 中的函数返回局部变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4824342/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
returning a local variable from function in C
提问by Mark
#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 -Wallthe 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!
有人可以对这个问题有所了解吗?提前致谢!
采纳答案by kelloti
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(),如果您忘记了,就会造成内存泄漏。
回答by Cam
For foo1(), you return a copyof 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.
对于其他函数,您返回指向局部变量的指针的副本。但是,该局部变量在函数完成时被释放,因此如果您之后尝试引用它,最终会遇到令人讨厌的问题。
回答by Keith Irwin
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 保留的空间不会被重新分配或重用,直到它通过调用 free 显式释放。
回答by evandrix
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.
是的,您正在返回一个数组,它实际上是幕后的一个指针,指向存储您初始化的变量内容的内存位置的地址。因此,它警告您返回这样的结果可能不是很有用,而您实际上可能是指数组值之一。

