user1777900
user1777900

Reputation: 985

C - reading past end of file with fgetc

I have the weirdest thing happening, and I'm not quite sure why it's happening. Basically what I need to do is use fgetc to get the contents of a simple ASCII file byte by byte. The weird part is it worked, but then I added a few more characters and all of a sudden it added a newline that wasn't there and read past the end of the file or something. Literally all I did was

do {
    temp = (char*) checked_realloc (temp, n+1);
    e = fgetc(get_next_byte_argument);
    temp[n] = e;
    if (e != EOF)
      n++;
 }
while (e != EOF);

And then to check I just printed each character out

temp_size = strlen(temp)-1;
for(debug_k = 0; debug_k < temp_size; debug_k++){
  printf("%c", temp[debug_k]);
}

And it outputs everything correctly except it added an extra newline that wasn't in the file. Before that, I had

temp_size = strlen(temp);

But then it ended on some unknown byte (that printed gibberish). I tried strlen(temp)-2 just in case and it worked for that particular file, but then I added an extra "a" to the end and it broke again.

I'm honestly stumped. I have no idea why it's doing this.

EDIT: checked_realloc is just realloc but with a quick check to make sure I'm not out of memory. I realize this is not the most efficient way to do this, but I'm more worried about why I seem to be magically reading in extra bytes.

Upvotes: 4

Views: 1703

Answers (2)

askmish
askmish

Reputation: 6674

A safer way to write such operation is:

  1. memset the memory bulk before use with zeros, if you are allocating memory prior to realloc.And every time you realloc, initialize it to zero.
  2. If you are using a memory to access strings or use string functions on that memory always ensure you are terminating that memory with a NULL byte.

do{
    temp = (char*) checked_realloc (temp, n+1);//I guess you are starting n with 0? 
    temp[n]=0;
    e = fgetc(get_next_byte_argument);
    temp[n] = e;
    if (e != EOF)
        n++;
} while (e != EOF);
temp[n]=0;
n=0;

I guess the above code change should fix your issue. You don't need strlen -1 anymore. :)

Cheers.

Upvotes: 1

kmkaplan
kmkaplan

Reputation: 18960

It sounds like you forgot to null terminate your string. Add temp[n] = 0; just after the while.

Upvotes: 0

Related Questions