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

标签 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 这样的字符串 class(并让它管理所有的字符串缓冲区内存分配/清理) .

关于c - C中局部变量错误的函数返回地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22288871/

相关文章:

c - 有没有类似于字符串比较但针对整数的函数?

c - 这个功能是如何工作的?

c - 关于 C 编译器 asm 输出的另一个问题

c - 如何在内核中的一个数组中连接四个整数?

c - 结构对字体大小的贡献

c - 下三角矩阵在 0 时给出错误答案

c - 当数组不包含 null 终止符时,为什么 strlen() 返回奇怪的结果?

c - C 中的类型命名空间

c - 从 C 中的文件读取后,指针数组中的每个指针都存储相同的值

c - 用c打开rar文件