如何强制 C++ 从磁盘分配内存? [英] How to force C++ allocate memory from disk?

查看:50
本文介绍了如何强制 C++ 从磁盘分配内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有数千行 C++ 代码,它们在小文本文件上运行良好,但在大文本文件(例如 2 GB 大小)上崩溃.崩溃原因:应用占用内存.

I have thousands lines of C++ codes which work well on small text files, but crashes on huge text files (such as 2 GB size). Crash reason: app eats up memory.

是否可以从磁盘分配内存?因为在大多数情况下,硬盘空间比物理内存大得多.如果我可以从硬盘中为我的应用借用一些空间并在使用后将它们归还,那么我的应用几乎没有崩溃的机会.

Is it possible to allocate memory from disk? Because in most case, hard disk space is much bigger than physical memory. If I can borrow some space from hard disk for my app and return them back after use, then my app has little chance to crash.

以下是我的设计思路:

  1. 为文件映射创建一个临时文件(CreateFileMapping、OpenFileMapping)
  2. 强制我的应用从临时文件中分配内存
  3. 做一些清理工作:关闭FileMapping并删除临时文件

因为我现有的代码太多,如果我的设计思路合理,我不想重新设计我的项目.

Because I have so much existing code, if my design thought is reasonable, I don't want to redesign my project.

我不确定设计思想是否可以实现.有人可以帮我吗?

I'm not sure if the design thought is possible to implement. Anybody can help me?

PS:我使用的是 Visual C++ 2010.

PS: I'm using Visual C++ 2010.

推荐答案

我有数千行 C++ 代码,它们在小文本文件上运行良好,但在大文本文件(例如 2 GB 大小)上崩溃.崩溃原因:应用占用内存.

I have thousands lines of C++ codes which work well on small text files, but crashes on huge text files (such as 2 GB size). Crash reason: app eats up memory.

您正在尝试将整个文件加载到 32 位系统(或具有 2GB RAM 的 64 位系统,或在 64 位系统上运行的 32 位应用程序)上的内存中.在 32 位系统上,无论您做什么,2 GB 的文本文件都不适合内存,因为使用 32 位寻址,您可以在最大 2 GB 的 RAM 上运行,即使它有分页文件支持.

You're trying to load entire file into memory on 32bit system (or on 64bit system with 2GB of RAM, or in 32bit application running on 64bit system). On 32bit system 2 gigabyte text file will not fit into memory no matter what you do, because with 32bit addressing you can operate on 2 gigabytes of RAM max, even if it is backed by paging file.

解决方案.

  1. (最简单)逐行处理文件,无需将整个文件加载到内存中.
  2. 创建文件映射.即使使用文件映射,您也无法一次访问整个文件,但可以将其部分映射到内存中.

这篇关于如何强制 C++ 从磁盘分配内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆