Search code examples
ccharfgets

C fgets not getting full text


When I use this code

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

to get, for example, text that is this long

fosndjfnsondfnsnkdfsjndfoweoingfoweljksdnflwkengdfwoensldkfwejlnfkdlskdfnlskdnflskdnflksndlfknslkdnflkndlknfslnlfjnlksdnjfnjwnejnfwenfnjwenlfodnakdoifnkleroglknerolkdfgnrkldsfgnlskdfgnlksdfglndlfkngkldnslkgnlkfdnkglnklsndfklnglfdlskgknllkdglksdfkkngkresoirigknlsdf

(This text doesn't mean anything, it's just a test) and I return the char *d; it outputs this

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

Why are there those strange characters at the end?


Solution

  • You've defined c as a local variable in openFile. Assuming your read succeeds, you're returning its address in d. It's destroyed at the end of openFile, so d becomes a dangling pointer. Attempting to use it after openFile returns results in undefined behavior.

    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.