简体   繁体   English

如何检查内存限制

[英]how to check memory limits

I am trying to check if the memory limits in my OS works. 我试图检查我的操作系统中的内存限制是否有效。 So I am using this is simple c program: 所以我使用的这是简单的c程序:

#include <iostream>
#include <cstdlib>

int main()
{
    const size_t GB = 1024 * 1024 * 1024;
    const size_t mem = 1 * GB;
    std::cout << "allocating " << mem << " bytes" << std::endl;
    void* p = malloc(mem);
    if (p) { std::cout << "memory allocated" << std::endl; }
    else { std::cout << "cannot allocate memory" << std::endl; }
    char a;
    std::cin >> a;
    free(p);
}

I am compiling with -O0 but when I look to the performance monitor I see that my a.out is using only 128Kb. 我正在使用-O0编译,但是当我查看性能监视器时,我发现我的a.out仅使用128Kb。 Why I don't see 1 GB? 为什么我看不到1 GB?

You need to commit the memory. 你需要提交内存。 As long as you only reserve it you have allocated "virtual memory". 只要您保留它,您就已经分配了“虚拟内存”。 You commit with reading or writing the memory. 您承诺阅读或写入内存。 With your program just add 随你的程序添加

void* p = malloc(mem);
if (p) { 
    std::cout << "memory allocated" << std::endl;
    memset(p, 0, mem);
} else {
    std::cout << "cannot allocate memory" << std::endl; }

In the Windows operating system you can use the function VirtualQuery to see what chunks of memory are reserved and what is committed. 在Windows操作系统中,您可以使用VirtualQuery函数来查看保留了哪些内存块以及提交的内容。

The OS will only "use" the memory that you are actually touching, so it will not show on performance monitor or such like when unless you actually "use" the memory. 操作系统只会“使用”您实际触摸的内存,因此它不会显示在性能监视器上或类似于除非您实际“使用”内存的情况。 This is because some applications allocate large amounts of memory "just in case", and it would take a lot of extra time to ACTUALLY populate that memory into the process, when in fact it isn't being used. 这是因为一些应用程序“以防万一”分配大量内存,并且实际上它没有被使用时,实际上将该内存填充到进程中需要花费很多额外的时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM