I have the following C code, which tries to read a binary file, and print out the resulting 32 bit values as hex:
// hello.cpp file
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
int main()
{
int file_size; // font file size in bytes
int i;
std::cout << "Hello World\n";
std::string binary_data_file("font.dat");
struct stat statbuff;
stat(binary_data_file.c_str(), &statbuff);
file_size = statbuff.st_size;
void *data_buffer;
posix_memalign(&data_buffer, 4096, file_size);
std::ifstream data_input_file(binary_data_file.c_str(), std::ios::in | std::ios::binary);
data_input_file.read((char *) data_buffer, file_size);
data_input_file.close();
int * debug_buffer = (int * ) data_buffer;
for (int j = 0; j< 148481; j ) {
std::cout << "Data size: " << std::dec << file_size << std::endl;
std::cout << "Element: " << j << " Value: " << std::hex << *(debug_buffer j) << std::endl;
}
return 0;
}
This code causes a Segmentation Fault when j == 148480
Data size: 211200
Element: 148477 Value: 0
Data size: 211200
Element: 148478 Value: 0
Data size: 211200
Element: 148479 Value: 0
Data size: 211200
Segmentation fault (core dumped)
Why is this the case? Surely the buffer size should be equal to 211200, right, so j should be able to go up to 211200?
CodePudding user response:
You allocated 211200
bytes, but you're trying to access 148481 * sizeof(int)
bytes, which is far past the end of the buffer (and past the end of the file content).