从功能用C返回一个局部变量 [英] returning a local variable from function in C

查看:114
本文介绍了从功能用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\n", foo1());
    printf("foo2: %s\n", foo2());
    printf("foo3: %d, %d, %d\n", 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!

推荐答案

这里的问题是,当你创建局部变量它(这里的实施而有所不同)在栈中分配,因此无法使用,一旦函数执行结束后。在preferable方式是使用的malloc()保留非本地内存。这里的危险是,你必须释放(免费()),您分配使用一切的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天全站免登陆