MS Windows和Linux之间的标注差异

Calloc differences between MS Windows and Linux?

本文关键字:之间 Windows Linux MS      更新时间:2023-10-16

我给calloc内存写了一些代码,直到没有可用的代码为止。

#include <stdlib.h>
#include <iostream>
using namespace std;
int main() 
{
    int *p;
    int count = 0;
    while(1) 
    {
        int inc=1024*1024*sizeof(char);
        p=(int*) calloc(1,inc);
        count++;
        if(!p)
        {
            cout << "managed to allocate " << (count * 1024 * 1024) / 1000000000.0 << " gbn";
            return 1;
        }
    }
}

在Visual Studio中的Windows上执行上述代码,我得到以下结果:

managed to allocate 1.9881 gb
Press any key to continue . . .

然而,当我把它带到我的Linux系统中,并用以下代码编译和运行时:

g++ mem.cpp
./a.out 

这个过程过了一段时间就被操作系统扼杀了。

即使分配的内存不存在,calloc似乎也不会返回null?

如果是这样的话,那么我如何修改现有的代码以在Linux上获得与在Windows上相同的效果?

这是因为Linux"过度使用"内存。Linux上的进程可以分配比物理可用内存更多的内存。只有在实际使用内存时,才会分配物理内存。

当Linux耗尽可用的物理内存时,它会停止进程,直到内存释放。

您可以在全系统范围内使用以下功能禁用此行为:

sudo sysctl -w vm.overcommit_memory=2

它将确保所有分配的物理内存都在那里。这可能不是个好主意。许多程序都依赖于这种行为,并分配了大量从未使用过的内存。

消耗所有可用内存也不是一个好主意。您的程序可能不是无法分配内存的程序,也不是被OOM杀手杀死的程序。您正在影响系统中的所有进程。