2017-10-28 68 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的内容。