2015-11-10 65 views
-3

我有問題,當我試圖通過一個char *作爲參數,我的代碼是這樣的:分段故障而傳遞的char *爲參數 - ç

int main(int argc, char** argv) { 
    if(argc > 1) { 
     //not sure if I need this.. 
     char* base = malloc(strlen(argv[1]) + 1); 
     strcpy(base, argv[1]); 
     base[strlen(argv[1])] = '\0'; 

     printf("base is %s\n", base); //does it right 

     testFunction(base); 

     return 0; 
    } else { 
     //do something 
    } 
}; 

void testFunction(char* base) { 
    //do things 
    anotherFunction(base); 
}; 

void anotherFunction(char* base) { 
    char* command = malloc(52); 
    command = "cp .tmp.db "; 
    printf("Command before cat %s, base is %s\n", command, base); 
    strcat(command, base); //Segmentation fault 
    printf("Command I need %s\n", command); 
    //more things 
} 

我與./program base.db運行它,輸出如下:

base is base.db 
Command before cat cp .tmp.db, base is base.db 

然後它只是失敗:分段錯誤。我確定這是因爲我用gdb運行它而崩潰的那一行,但我不確定我在做什麼錯誤。我也嘗試用for循環打印base [i],但它具有相同的效果。 我擡頭看了其他的問題,但我解決不了這個問題。

我知道我應該看看malloc是否成功,我會加上後者,我想先解決這個問題。

+0

連續兩次分配到相同的變量,沒有人使用這個變量=>東西是最有可能是錯誤的。 –

+1

'base [strlen(argv [1])] ='\ 0';'是不必要的。切勿使用它。 –

+1

這不是必須的,因爲'strcpy()'拷貝了空終止符。 – Barmar

回答

3

當你以下

char* command = malloc(52); //this memory is wasted 
command = "cp .tmp.db "; //this is string constant, and is kept in read only memory 

後來,這裏

strcat(command,base); 

您試圖Concat的到只讀存儲器。


要糾正這一點,使用strcpy()

char* command = malloc(52); 
strcpy(command, "cp .tmp.db "); 
1

command = "cp .tmp.db ";應該strcpy(command, "cp .tmp.db ");

0

strcat的附加源字符串複製到目標字符串,所以目標應該有足夠的內存。

您爲命令變量分配了內存,但隨後爲其分配了文字值,因此命令將指針存儲到只讀內存。

修改你的代碼是這樣的:

char* command = (char*)calloc(128, sizeof(char)); 
strcpy(command, "cp .tmp.db "); 
printf("Command before cat %s, base is %s\n",command,base); 
strcat(command,base); 
printf("Command I need %s\n",command);