Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unexpected Behavior on printing a Char Set on C

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading