Aan*_*Aan 0 c windows malloc memory-management
我知道Windows 32位允许任何进程大约2千兆字节的内存地址空间.2千兆字节= 2147483648字节.我试图分配堆内存超过2147483648字节,我没有看到任何错误或异常,这个代码:
# include<iostream>
int main(){
void *x=malloc(2147489999);
free(x);
system("pause");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
是什么原因?
你没有检查返回值:)
#include <windows.h>
#include <malloc.h>
#include <stdio.h>
#include<iostream>
#define PAUSE getchar
int
main(int argc, char *argv[])
{
void *x=malloc(2147489999);
if (x)
{
printf ("malloc succeeded: 0x%x...\n", x);
free(x);
}
else
{
perror ("malloc failed");
}
PAUSE ();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
C:\ temp>\bin\vcvars32设置使用Microsoft Visual C++工具的环境.C:\ temp> notepad tmp.cpp
C:\ temp> cl tmp.cpp Microsoft(R)32位C/C++优化编译器版本12.00.8168(适用于80x86)版权所有(C)Microsoft Corp 1984-1998.版权所有.
tmp.cpp ... /out:tmp.exe tmp.obj
C:\ temp> tmp malloc失败:没有错误