std :: string - > execvp等

时间:2012-05-11 20:00:48

标签: c++ exec

我刚刚在一个程序中发现了一个难以捉摸的错误,结果是因为启用了优化,在下面的某些内容中,有时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等中使用?

1 个答案:

答案 0 :(得分: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

糟糕的主意。