0

我刚刚在程序中发现了一个难以捉摸的错误,结果证明是因为启用了优化,在类似以下的情况下,有时 std::string 在 processDocument() 从中获取文本之前被破坏:

#include <stdio.h>
#include <spawn.h>
#include <string>
static void processDocument(const char* text) {
        const char* const argv[] = {
                "echo",
                text,
                NULL,
        };
        pid_t p;
        posix_spawnp(&p, "echo", NULL, NULL, (char**) argv, environ);
}
static int mark = 'A';
static void createDocument() {
        const char* vc;
        std::string v = "ABCKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK42";
        ++mark;
        v[0] = mark;
        vc = v.c_str();
        processDocument(vc);
}
int main() {
        createDocument();
        createDocument();
        return(0);
}

如何安全地将 std::string 转换为 char* 以用于 execvp、posix_spawnp 等?

4

1 回答 1

1

我发现了它的真正原因(这里是实际的最小测试用例):

std::string resultString;
const char* nodeText;
const char* altText;
resultString = "......whatever1.";
nodeText = resultString.c_str();
resultString = ".....whatever2..";
altText = resultString.c_str();
printf("%s\n", nodeText); // garbage

馊主意。

于 2012-05-13T12:22:11.237 回答