从 C 中的函数返回局部变量 [英] returning a local variable from function in C

查看:41
本文介绍了从 C 中的函数返回局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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
", foo1());
    printf("foo2: %s
", foo2());
    printf("foo3: %d, %d, %d
", p[0], p[1], p[2]);
    return 0;
}

当我使用 gcc -ansi -pedantic -W -Wall 编译它时,编译器会针对 foo2() 和 foo3() 发出警告消息:

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

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

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!

推荐答案

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

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.

这篇关于从 C 中的函数返回局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆