我有以下代码:
char* gen()
{
char out[256];
sprintf(out, ...); // you don't need to know what's in here I don't think
return out;
}
当我尝试编译时出现此错误:
ERROR: function returns address of local variable
我试过返回 char[]
和 char
但没有成功。我错过了什么吗?
最佳答案
您的 char
数组变量 out
仅存在于函数体的内部。
当您从函数返回时,无法再访问 out
缓冲区的内容,它只是函数的本地。
如果你想从你的函数返回一些字符串给调用者,你可以动态在函数内部分配那个字符串(例如使用malloc()
)并返回一个指向调用者的字符串的指针,例如
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*
参数以及缓冲区大小(以避免缓冲区溢出)传递。
在这种情况下,您的函数可以直接将字符串格式化为作为参数传递的目标缓冲区:
/* 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++,最简单的做法是使用一个像 std::string
这样的字符串 class(并让它管理所有的字符串缓冲区内存分配/清理) .
关于c - C中局部变量错误的函数返回地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22288871/