Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fread storing random characters in buffer

I'm simply trying to read a file using fread and output the contents. It's partially working. It outputs everything correctly but it ends with a bunch of random characters.

#include <iostream>

using namespace std;

void ReadFile(char* filename,char*& buffer)
{
    FILE *file = fopen(filename,"rb");

    fseek(file,0,SEEK_END);
    int size = ftell(file);
    rewind(file);

    buffer = new char[size];
    memset(buffer,0,size);

    int r = fread(buffer,1,size,file);
    cout << buffer;

    fclose(file);
}

int main()
{
    char* buffer;
    ReadFile("test.txt",buffer);
    cin.get();
}

Let's say 'size' is 50 in this instance. for some reason, the size of buffer ends up 55 or 56 after fread is called. I emptied the buffer before using it and tried outputting it, everything is normal (it's empty). Right after the call to fread the buffer somehow gets bigger and is filled with random characters. I've opened the text file in a hex editor to ensure there isn't anything I'm not seeing but there isn't. The file is 50 bytes. fread returns the amount of bytes read, in this case returned to 'r', 'r' is what it should be. so where the mother eff are these bytes coming from?

simplified: fread returns correct amount of bytes read but the buffer somehow makes itself bigger after fread is called, then fills it with random characters. why?

I can't for the life of me figure out how this is happening.

Also, before anyone gives me an easy fix, I already know I could just do buffer[r] = '\0' and not have it output anymore random characters but I'd much rather know WHY this is happening.

like image 814
David Avatar asked Mar 07 '26 08:03

David


1 Answers

cout's << operator on char* expects C strings, so you need to null-terminate your buffer:

int size = ftell(file)+1; // Leave space for null terminator
...
int r = fread(buffer,1,size-1,file); 
buffer[r] = '\0';
cout << buffer;

The extra characters that you see is random data in the memory addresses after the end of your buffer. operator << does not know that the string has ended, so it continues printing until it finds the first '\0' byte.

like image 185
Sergey Kalinichenko Avatar answered Mar 09 '26 23:03

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!