C中局部变量错误的函数返回地址 [英] Function returning address of local variable error in C

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

问题描述

我有以下代码:

 char* gen()
 {
     char out[256];
     sprintf(out, ...); // you don't need to know what's in here I don't think

     return out;
 }

尝试编译时出现此错误:

And I am getting this error when I try to compile:

ERROR: function returns address of local variable

我尝试过这种返回 char [] char 的方法,但是没有运气.我想念什么吗?

I've tried having this return char[] and char with no luck. Am I missing something?

推荐答案

您的 char 数组变量 out 仅在函数主体内部内部存在.
当您从函数返回时, out 缓冲区的内容将无法再访问,它仅是函数的 local .

Your char array variable out exists only inside the function's body.
When you return from the function, the content of out buffer can't be accessed anymore, it's just local to the function.

如果您想从函数中返回一些字符串给调用者,则可以动态在函数内部分配该字符串(例如,使用 malloc())并返回一个指向呼叫者的字符串的 pointer ,例如

If you want to return some string from your function to the caller, you can dynamically allocate that string inside the function (e.g. using malloc()) and return a pointer to that string to the caller, e.g.

char* gen(void)
{   
    char out[256];
    sprintf(out, ...);

/* 
 *   This does NOT work, since "out" is local to the function.
 *
 *   return out;
 */

    /* Dynamically allocate the string */
    char* result = malloc(strlen(out) + 1) /* +1 for terminating NUL */

    /* Deep-copy the string from temporary buffer to return value buffer */
    strcpy(result, out);

    /* Return the pointer to the dynamically allocated buffer */
    return result;
    /* NOTE: The caller must FREE this memory using free(). */
}

另一个更简单的选择是将 out 缓冲区指针作为 char * 参数传递,并带有缓冲区大小(以避免缓冲区溢出).

Another simpler option would be to pass the out buffer pointer as a char* parameter, along with a buffer size (to avoid buffer overruns).

在这种情况下,您的函数可以将字符串直接格式化为作为参数传递的目标缓冲区:

In this case, your function can directly format the string into the destination buffer passed as parameter:

/* Pass destination buffer pointer and buffer size */
void gen(char* out, size_t out_size)
{   
    /* Directly write into caller supplied buffer. 
     * Note: Use a "safe" function like snprintf(), to avoid buffer overruns.
     */
    snprintf(out, out_size, ...);
    ...
}

请注意,您在问题标题中明确指出了"C",但添加了 [c ++] 标记.如果可以使用C ++,最简单的方法是使用字符串 class ,例如 std :: string (并让它管理所有字符串缓冲区的内存分配/清除).

Note that you explicitly stated "C" in your question title, but you added a [c++] tag. If you can use C++, the simplest thing to do is to use a string class like std::string (and let it manage all the string buffer memory allocation/cleanup).

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

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