简体   繁体   中英

Unexpected behaviour from function reading file in C

Ok, I'll start of by saying that i'm making a webserver. And i have a function getFileContent i use to get my content from my files that looks like this

char* getFileContent(char *filename)
{
    long length;
    char *buffer;
    FILE *f = fopen (filename, "r");
    if (f) {
        fseek (f, 0, SEEK_END);
        length = ftell (f);
        fseek (f, 0, SEEK_SET);
        buffer = malloc (length + 1);
        if (buffer) {
            fread (buffer, 1, length, f);
        }
        fclose (f);
    }

    if (buffer != 0) {
        return buffer;
    } else {
        return NULL;
    }
}

And when calling this function i get some weird behaviour.
If i only call it once like this
char *fileContent = getFileContent(path);
for example when i'm getting the filecontent to return, it appends a 2 or 3 weird characters.
But if i call it twice to the same variable, it appends another set of weird characters.

However, if i call the function a third time, at the beginning of the program, in main . By for example getting the content in /etc/hosts/ to a completely different and unused variable, it prints the output normally later in the code.

I've tried to see the problem but it seems so random and i'd really appreciate it if anyone could help me with it.

When you read the file content, your buffer is not NUL terminated. So if you're treating it as a C-string (eg printf), you're invoking undefined behavior.

You should check the return value of fread and place a '\\0' after the last byte read.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM