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

查看:41
本文介绍了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())并返回一个指针指向调用者的那个字符串,例如

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++,最简单的做法是使用一个字符串 classstd::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天全站免登陆