2017-10-28 66 views
0

我碰到一個困惑的問題來了,當我用CC字符串修改

程序時,我使用oldPacket.filename = "fallout.jpg" //我有一個名爲fallout.jpg文件和一個名爲oldPakcet結構用的char *類型的文件名

該程序運行得很好

現在,我決定讓用戶輸入文件名,並檢查文件的存在。我寫了下面的功能:

bool Searchfile(packet* ptr) { 
    char userinput[100]; 
    fgets(userinput, sizeof (userinput), stdin); //non terminated input by fgets 
    userinput[strcspn(userinput, "\n")] = 0; 
    //printf("%d\n",strlen(userinput)); 
    ptr->filename = userinput + 4;//i skip the first 4 char since the correnct format is ftp <filename> 
    printf("%s\n",ptr->filename); 
    printf("%d\n",strlen(ptr->filename)); 
    ptr->filename[strlen(ptr->filename)] = '\0'; 
    if (access(ptr->filename, F_OK) != -1) { 
     printf("exist\n"); 
     return false; 
    } else { 
     //printf("does not exist\n"); 
     return true; 
    } 
} 

我調用由

while (Searchfile(&oldPacket)){ 
    printf("Please input the file name in the format: ftp <file name> \n"); 
} 

這個功能但是該程序不再工作,它顯示了賽格故障在

int filesize; 
    fp = fopen(oldPacket.filename, "rb"); 
    fseek(fp, 0L, SEEK_END);//here is the seg fault 

任何人有一些想法,爲什麼這發生了嗎?

我已經在printf文件名的每個字符,它看起來正確....提前

感謝

+0

您返回一個指向堆棧中超出範圍的變量的指針。 – orhtej2

+1

同樣查看seg故障的位置,您可能會對「fp」的值感興趣。 –

回答

2

你讓ptr->filename點局部變量userinput的地址,並訪問該值一旦userinput已超出範圍是未定義的行爲。

段錯誤的原因可能是filename的值在Searchfile之外訪問時可能是垃圾,因此該文件將不會被打開。隨後fseek然後將一個NULL - 值對fp叫...

一個簡單的方法來克服,這將是寫static char userinput[100];,至少當你在多線程環境中無法正常工作。否則,您必須預留內存ptr->filename並複製userinput的內容。