Home > Software engineering >  Unexpected Behavior on printing a Char Set on C
Unexpected Behavior on printing a Char Set on C

Time:06-11

I am getting these unexpected chars when I try to print the string inside of a file. How can I deal with this situation?

This is my code:

#include <stdlib.h>
#include <stdio.h>

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

int main() {

    char *firstS = readFile("file.txt");
    printf("%s \n", firstS);

    return 0;
}

CodePudding user response:

You're not NUL terminating your string. Instead, do

buffer = malloc(length 1);

and then after you read in the file

buffer[length] = '\0';

When printf reads past the allocated memory for buffer, it invokes undefined behavior, printf happily reads along until it finds a '\0'. Also note you should initialize buffer to NULL:

char * buffer = NULL;

and check for that back in main before you print. If there's a problem opening the file for instance, you return an uninitialized buffer to main, and trying to read from that is another UB invoker:

char *firstS = readFile("file.txt");
if (firstS != NULL)
{
    printf("%s \n", firstS);
}
else
{
    // print error message to your liking
}
  • Related