Access violaton while Reading from a binary file into a char * buffer

1

I wrote a binary file using ofstream, starting from an array of float. When I open it with notepad++ I see a single line of ASCII symbols. The size shown in File Explorer is 19922944 bytes.

Now I'm trying to read it using ifstream:

size_t fileSize = sizeof(char)*19922944; // this value is coherent with the original buffer size and it's the same exact size that I can see from File Explorer
char *fileBuffer = new char(lSize);
std::ifstream iFile("C:\\TheFile.dat", std::ios::in | std::ios::binary);
iFile.read( fileBuffer, fileSize); // 0xC0000005 Access violation writing location 
iFile.close();

If, instead, I read a smaller size, like fileSize=2000, it works well. But, again, the size on disk is 19922944. Any idea of what can be wrong?

c++
asked on Stack Overflow Aug 1, 2019 by HAL9000

2 Answers

6
char *fileBuffer = new char(lSize);

is wrong. It allocates memory for only one char. You need to use

char *fileBuffer = new char[lSize];

It will be preferable to use std::string so your code does't have to worry about memory management.

std::string fileBuffer(lSize, ' ');
iFile.read(fileBuffer.data(), fileSize);
answered on Stack Overflow Aug 1, 2019 by R Sahu • edited Aug 1, 2019 by R Sahu
2

Assuming that you meant char *fileBuffer = new char(fileSize); you're allocating a single character and initializing it with a value that is way too large to store in a single character.

If you enable your compiler's warnings, it is likely to alert you to this sort of problem.

For instance, MSVC 2015 says:

warning C4267: 'initializing': conversion from 'size_t' to 'char', possible loss of data

answered on Stack Overflow Aug 1, 2019 by Sid S

User contributions licensed under CC BY-SA 3.0