【问题标题】:Why does C++ posix_memalign give the wrong array size?为什么 C++ posix_memalign 给出错误的数组大小?
【发布时间】:2022-06-10 22:59:45
【问题描述】:

我有以下 C++ 代码,它尝试读取二进制文件,并将生成的 32 位值打印为十六进制:

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;
}

当 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)

为什么会这样?当然缓冲区大小应该等于211200,对吧,所以j应该可以达到211200?

【问题讨论】:

  • 传递给posix_memalign 的大小是字节数。您的 j 是许多 int 元素。 int 在您的 C++ 实现中,每个元素可能是四个字节。那么在 211,200 字节中只有 211,200/4 = 52,800 int 元素可用。在未来的调试问题中,始终包含minimal reproducible example

标签: c++


【解决方案1】:

您分配了211200 字节,但您尝试访问148481 * sizeof(int) 字节,这远远超出了缓冲区的末尾(并且超出了文件内容的末尾)。

【讨论】:

    猜你喜欢
    • 2021-11-12
    • 1970-01-01
    • 2021-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-20
    • 2018-08-15
    相关资源
    最近更新 更多