簡體   English   中英

將 char* 作為參數傳遞時出現分段錯誤 - c

[英]segmentation fault while passing char* as parameter - c

當我嘗試將 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是否成功,我會在后面添加它,我想先解決這個問題。

當您執行以下操作時

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);

您正在嘗試連接到只讀內存。


要糾正此問題,請使用strcpy()

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

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

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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM