如何将 const char* 从函数转移到函数?

Fra*_*act 4 c++ string

这是我正在尝试做的一个例子:

#include <stdio.h>

FILE* f;
const char* getstring()
{
    f = fopen ("hello.txt", "r");
    char x[200];
    for (int i = 0; i < 200; i++) x[i] = 0;
    for (int c = getc(f), i = 0; (c != EOF) && (i < 200); c = getc(f), i++)
        x[i] = c;
    fclose(f);
    printf ("getstring(): x = %s", x);
    const char* y = x;
    printf ("getstring(): y = %s", y);
    return y;
}

void printstring (const char* string)
{
    printf ("%s", string);
}

int main()
{
    printstring(getstring());
    printf ("\nprintf: %s", getstring());
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出是:

getstring(): x = Hello World
getstring(): y = Hello World
???getstring(): x = Hello World
getstring(): y = Hello World

printf: ????????
Run Code Online (Sandbox Code Playgroud)

我不知道为什么该printstring()函数什么都不输出,printf而是输出随机数据,或者为什么string在我使用该printstring()函数时在末尾有一些随机数据。

有什么办法可以解决这个问题,我做错了什么?

Chr*_*phe 6

问题

问题是getstring()返回一个指向本地数组的指针。这个数组在函数返回时被破坏,所以你有一个悬空指针。使用这个指针是未定义的行为。任何事情都可能发生:例如,您可以获得垃圾随机值,您可以获得旧的未更改值,或者系统可能崩溃。

解决方案

由于这个问题被标记为 c++,只需使用std::string而不是char*,这种噩梦就会消失。

请注意,使用std::stringinprinf()将要求您获得带有 .c_str().

如果出于某种模糊的原因,您需要使用,则必须为 c 字符串char*使用strdup()或分配一些内存并返回指向该内存的指针。但是如果你不想内存泄漏,调用者必须删除这个指针。

  • @Christophe [未定义的行为可能导致时间旅行(除其他外,但时间旅行是最有趣的)](https://devblogs.microsoft.com/oldnewthing/20140627-00/?p=633)利用实际时间-旅行留给读者作为练习。 (2认同)