[英]Function returning address of local variable error in C
我有以下代码:
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
这样的字符串类(并让它管理所有字符串缓冲区内存分配/清理)。
问题是当函数gen
返回(退出)时,它的局部变量(例如out
)超出了作用域并且调用者不再可以访问它。 因此,当您返回out
您会返回一个指向不再分配的内存的指针。
从函数“返回”指针/缓冲区有两种选择:
在调用函数中分配缓冲区并将其传递给gen
:
char out[256]; gen(out, sizeof out);
通常还提供您传入的缓冲区的大小,因为被调用的函数无法知道这一点。 这意味着您必须将 gen 的声明更改为:
void gen(char * out, size_t size){
您还可以将传入缓冲区的大小硬编码为 256(因为您现在已在gen
函数中对其进行了硬编码):
void gen(char out[256]){
这意味着您必须向gen
提供一个char[256]
类型的变量(并且没有其他指针或数组)。 但它确实允许您在gen
内部执行sizeof out
。
在函数内部动态分配缓冲区:
char * out = malloc(256 * sizeof *out); // ... return out;
这样做的好处是gen
的声明不会改变。 但这确实意味着调用函数在完成后必须free
返回的缓冲区。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.