远程登录工作站(64G)c语言分配12G内存失败
代码如下
#include<stdio.h>
#include<string.h>
#include<malloc.h>
int main()
{
char *x=NULL;
x=(char *)calloc(3001*3001*1200,sizeof(char));
if(x==NULL)
printf("failed");
else printf("success");
return 0;
}
结果是failed
一个程序,可以使用的堆栈数量是有效的,不是电脑内存有多少你的程序就能用多少!毕竟,系统不可能是设计的只运行一个,或者几个程序。
哦,那该如何扩大程序的运行空间呢
每个进程分配的虚拟地址空间有限制。
Maybe you should try malloc install of calloc, you should recognize the differences between them.
qq332982511 :
哦,那该如何扩大程序的运行空间呢
没办法,linux内核已经定义好一个进程用户空间最大只有3G的虚拟内存。
我不知道你为什么需要如此多的虚拟内存,如果你是为了测试内核能给你最大分配多少内粗,理论值就是3G,实际上你也不可能能分配到3G。
你只要记住是内核已经规定好的就OK了。
如果你确实需要这么多,而且你的物理内存也足够大。你可以分成几个进程并行处理,通过IPC传递数据就好了。
linux下虚拟内存为4GB,有1GB是供内核使用,3GB供应用层使用
用内存映射文件代替内存。
http://blog.csdn.net/yasaken/article/details/7229076
1TB也能分配
#include
#include
#include
#include
#include
#include
#include
int main(int argc,char**argv)
{
char *x=NULL;
int fd;
if((fd=open(argv[1],O_RDWR))==-1)
{
printf("failed to open\n");
}
x=mmap(0,3001*3001*1200*sizeof(char),PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
if(x==NULL)
printf("failed\n");
else
printf("x=0x%x\n",x);
return 0;
}
#include<stdio.h>
#include<string.h>
#include<malloc.h>
#include<sys/mman.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
int main(int argc,char**argv)
{
char *x=NULL;
int fd;
if((fd=open(argv[1],O_RDWR))==-1)
{
printf("failed to open\n");
}
x=mmap(0,3001*3001*1200*sizeof(char),PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
if(x==NULL)
printf("failed\n");
else
printf("x=0x%x\n",x);
return 0;
}
这是参照Unix高级编程实现的映射I/O。可以成功运行。