gpt4 book ai didi

c - C 中函数返回局部变量错误的地址

转载 作者:行者123 更新时间:2023-11-30 16:12:15 25 4
gpt4 key购买 nike

我有以下代码:

 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/58377447/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com