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?
您分配211200
字节,但您试图访问148481 * sizeof(int)
字节,这远远超出了缓冲区的末尾(并且超出了文件内容的末尾)。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.