1

当我使用此代码时

char *openFile(const char file[1024]){
FILE *f = fopen(file, "r");
char c[1000];
char *d;
if (f!=NULL) {
    if (fgets(c, 1000, f) !=NULL){
        d = c;
    }
    else{
        d = "No text";
    }
}
else{
    d="error";
    printf("%s", d);
}
fclose(f);

return d;
}

例如,获取这么长的文本

fosndjfnsondfnsnkdfsjndfoweoingfoweljksdnflwkengdfwoensldkfwejlnfkdlskdfnlskdnflskdnflksndlfknslkdnflkndlknfslnlfjnlksdnjfnjwnejnfwenfnjwenlfodnakdoifnkleroglknerolkdfgnrkldsfgnlskdfgnlksdfglndlfkngkldnslkgnlkfdnkglnklsndfklnglfdlskgknllkdglksdfkkngkresoirigknlsdf

(这个文本没有任何意义,它只是一个测试)我返回char *d;它输出这个

fosndjfnsondfnsnkdfsjndfoweoingfoweljksdnflwkengdfwoensldkfwejlnfkdlskdfnlskdnflskdnflksndlfknslkdnflkndlknfslnlfjnlksdnjfnjwnejnfwenfnjwenlfodnakdoifnkleroglknerolkdfgnrkldsfgnlskdfgnlksdfglndlfkngkldnslkgnlkfdnkglnklsndfklnglfdlskgknllkdglksdfkkngkresoir¯ˇˇˇˇˇˇˇv”[

为什么最后会有那些奇怪的角色?

4

1 回答 1

3

您已copenFile. 假设您的读取成功,您将在d. 它在 结束时被销毁openFile,因此d成为一个悬空指针。在返回后尝试使用它会openFile导致未定义的行为。

Possible cures include defining c as static, and returning a buffer allocated with malloc instead. Defining c as static has a fair number of pitfalls, especially when/if multi-threading gets involved, so dynamic allocation is often quite a bit cleaner.

于 2013-03-09T16:07:58.387 回答