我有問題,當我試圖通過一個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是否成功,我會加上後者,我想先解決這個問題。
連續兩次分配到相同的變量,沒有人使用這個變量=>東西是最有可能是錯誤的。 –
'base [strlen(argv [1])] ='\ 0';'是不必要的。切勿使用它。 –
這不是必須的,因爲'strcpy()'拷貝了空終止符。 – Barmar