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

动态分配2GB内存却未被系统监视器检测到的问题求助

问题原因及解决办法
  • 核心问题:操作系统的延迟内存分配机制
    你用new申请内存时,操作系统只是给进程预留了虚拟地址空间,并没有立刻分配实际的物理内存。只有当你往这块内存里写入数据时,内核才会触发缺页中断,把物理内存页映射到虚拟地址上,这时系统监视器才能看到内存占用上升。

  • 解决方式:触发物理内存分配
    修改代码,在每次分配内存后写入数据,强制系统分配物理内存,比如用memset填充内存:

    #include <iostream>
    #include <thread>
    #include <cstdint>
    #include <cstring> // 要包含memset的头文件
    
    using namespace std;
    
    int main()
    {               
        long long unsigned j = 0;
        while(true)
        {
            int * pt = new int32_t[250 * 1000 * 10]; //10MB
            memset(pt, 0, sizeof(int32_t) * 250 * 1000 * 10); // 写入数据触发物理分配
            static long long unsigned int m2GB = 200; //loop rounds needed to allocate 2GB
            j++;
            if(j % 10 == 0) //100MB per 100MB
            {
                cout << (j*10) << "MB allocated" << endl;
                this_thread::sleep_for(100ms);
            }
            if(j >= m2GB)
                break;
        }
    
        cout << "Type sth to close" << endl;
        cin >> j; //blocking
    }
    

    运行修改后的代码,系统监视器就能看到内存占用逐步上升到2GB的峰值了。

  • 补充说明
    延迟分配是Linux、Windows、macOS等现代操作系统的通用策略,目的是避免内存资源浪费——如果进程申请了内存却一直不用,这些内存可以留给其他进程使用。

内容的提问来源于stack exchange,提问作者R. Absil

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 11:26:52