0

When reading a file, I am given garbage data from my program, such as ���! at the end of the string. Why is this happening?

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

char *
read_kernel(char *filename)
{   // Reads a kernel into a string in memory
    char *text = NULL;
    int length;
    FILE *file = fopen(filename, "r");

    // Return null if the kernel fails to load
    if (file == NULL)
    return NULL;

    // Find the file size
    fseek(file, 0, SEEK_END);
    length = ftell(file);
    rewind(file);

    //text = (char *) malloc(sizeof(char) * length);
    text = (char *) malloc(sizeof(char) * (length + 1));
    if (text == NULL)
        return NULL;

    // read the file's text into the text buffer
    fread(text, length, 1, file);
    fclose(file);
    file = NULL;

    text[length] = '\0'; // added zero terminator
    return text;
}
user1876508
  • 12,864
  • 21
  • 68
  • 105
  • 4
    Looks like you forgot the NUL byte at the end of the string. Allocate `length + 1` bytes then set `text[length] = '\0';`. –  Apr 18 '14 at 22:09
  • probably because it is not zero terminated – Davlog Apr 18 '14 at 22:09
  • Yep, it needed to be zero terminated. Thanks for the help. – user1876508 Apr 18 '14 at 22:13
  • Watch out with "r" as an argument to `fopen`. You state you are reading "text", but then you use `ftell` and `fread`. For safety, use "rb". See also http://stackoverflow.com/questions/2174889/whats-the-differences-between-r-and-rb-in-fopen – Jongware Apr 18 '14 at 22:23
  • 2
    @Jongware Good point, but you might want to also mention that this really only matters on Windows platforms\*. In Linux (and presumably Mac as well), "rb", "rt", and "r" are all identical, and the "t" and "b" flags are supported only for code compatibility with Windows. \*(and perhaps some other relatively obscure platforms that use multi-character line endings, although I can't name any off the top of my head) – Mike Holt Apr 18 '14 at 22:43
  • @MikeHolt: thanks for those comments. I've been switching between Mac and Windows programming for so long, I've developed my own way of dealing with about every possible permutation of line endings: an `\n` *possibly* followed by an `\r`, and the other way around, constitutes a single line end. Works even in mixed-mode files. – Jongware Apr 18 '14 at 22:56

0 Answers0