2012-05-11 55 views
0

我剛剛在程序中發現了一個難以捉摸的bug,結果是因爲啓用了優化,在下面這樣的東西中,有時std :: string在processDocument()得到文本出來的:std :: string - > execvp等

#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等?

+0

相關:http://stackoverflow.com/questions/7107305/sharing-data-across-processes-on-linux –

+2

你共享的程序不應該按照你描述的方式行事。你見過**確切的程序**會產生不正確的結果嗎? –

+0

無論是在這個程序還是你的原始程序中,你看到了什麼樣的行爲導致你相信「在processDocument()獲得文本之前,std :: string被銷燬了」? –

回答

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 

壞主意。

相關問題