You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Boost Interprocess创建大于4GB的内存映射文件?

如何用Boost Interprocess创建大于4GB的内存映射文件?

问题原因

你的代码中unsigned int sizeInMB是32位无符号整数,当计算5 * 1024 * 1024 * 1024(即5GB)时,该值超过了32位无符号整数的最大值(4294967295,约4GB),触发整数溢出。溢出后实际传入的大小变为5GB - 4GB = 1GB,这就是file2可用内存仅为1GB的原因。

解决方案

使用64位整数类型存储文件大小,避免溢出问题,同时确保运行环境为64位系统(32位系统本身无法支持超过4GB的内存映射)。修改后的代码如下:

#include <iostream>
#include <string>
#include <cstdint>

#include <boost/interprocess/managed_mapped_file.hpp>

int main()
{
    // 使用size_t(64位系统下为64位整数)或uint64_t明确指定64位类型
    size_t sizeInMB = 4 * 1024 - 1;
    boost::interprocess::managed_mapped_file file1(boost::interprocess::create_only, "MyMappedFile1", sizeInMB * 1024 * 1024);
    std::cout << "Free memory File 1 = " << file1.get_segment_manager()->get_free_memory() << std::endl;

    sizeInMB = 5 * 1024;
    boost::interprocess::managed_mapped_file file2(boost::interprocess::create_only, "MyMappedFile2", sizeInMB * 1024 * 1024);
    std::cout << "Free memory File 2 = " << file2.get_segment_manager()->get_free_memory() << std::endl;
}

额外注意事项

  • 确保编译和运行环境为64位,32位系统的地址空间限制无法支持超过4GB的内存映射。
  • 目标文件系统需支持大文件(如NTFS、ext4),FAT32等文件系统单个文件最大仅支持4GB。

内容的提问来源于stack exchange,提问作者user1474341

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 17:52:22