MS Windows和Linux之间的标注差异
Calloc differences between MS Windows and Linux?
我给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杀手杀死的程序。您正在影响系统中的所有进程。
相关文章:
- Windows 和 Linux 之间的相对路径分辨率差异?
- Raspbian-Windows openCV videostream之间的套接字
- Visual Studio 2015:在远程编译(在Raspberry上)和本地编译(在Windows上)之间切换
- Windows和Ubuntu的Bash之间的G 差异
- C 和Windows OS之间的关系
- 在两个Windows QT5之间进行通信
- 在QT中的Windows之间传递信息
- Windows和原生Android之间的std::shared_ptr差异
- std::map 实现在 Linux 和 Windows 之间有所不同
- 使用 NamedPipe 访问 Windows 服务之间的安全性
- 在QT应用程序和Windows Explorer之间剪切和粘贴剪贴板交换
- Windows 和 Linux 中的 USB Serial 之间的区别
- MFC和Windows API之间的区别在获取屏幕分辨率方面
- Linux 和 Windows wchar_t之间的差异和转换
- 如何在Visual Studio中进行串行端口编程C++Windows和Linux之间的可移植性?
- Windows和Linux之间的文件差
- windows DLL是否有可能在多个线程或进程之间使用相同的套接字编号
- 在 2 个程序 (Windows) 之间传输信息
- 两个 C++ 可执行对象之间的实时数据通信,一个是 Windows 和另一个在虚拟机 Ubuntu 中
- Windows 7和Windows 8.1之间的堆栈地址差异