How to dynamically allocate big memory , like 10 G ,using new operator in c++ on 64-linux? -
i need dynamically allocate larger float array special application using c++ new operator, 10g. code running on 64-ubuntu-14.04 linux os 64g memory. when set request of memory 7g ,1879048192x4/(1024x1024x1024)=7g
(float has 4 bytes), :
float * data; data = new float[1879048192];
the program works well, when try increase request 10g , got what(): std::bad_alloc
. try use malloc()
take place of new operator:
data =(float*)malloc(1879048192*sizeof(float));
but obtain same result. ulimit -a
this:
core file size (blocks, -c) 0 data seg size (kbytes, -d) unlimited scheduling priority (-e) 0 file size (blocks, -f) unlimited pending signals (-i) 514689 max locked memory (kbytes, -l) 64 max memory size (kbytes, -m) unlimited open files (-n) 1024 pipe size (512 bytes, -p) 8 posix message queues (bytes, -q) 819200 real-time priority (-r) 0 stack size (kbytes, -s) 8192 cpu time (seconds, -t) unlimited max user processes (-u) 514689 virtual memory (kbytes, -v) unlimited file locks (-x) unlimited
someone may there might no 10g continual memory allocation, close other progresses , total memory 64g. want know whether can obtain larger array or not, , how. linux limit max number dynamically allocation? , how?
i don't see problem when try it. both new
, malloc
worked. system runs ubuntu 15.04 , has 16g of ram.
however, if try use memory, found needed careful types of vars used index data array.
for instance, program below can undesirable things long int
and float
, because long int
has max value of 2^31
, array length 10gi longer 2^31
. also, floats add 1.0
@ time 16777216.0
. doubles, ok use long int indexes here because array shorter.
use10g.c++
#include <stdio.h> #include <stdlib.h> int main(int argc, char **argv){ long long int ten = 10; long long int megi = 1024*1024; long long int gigi = 1024*megi; long long int asize = (ten*gigi)/((long int) sizeof(double)); double * data = new double[asize]; long long int i=2; printf("a double %zd bytes\n", (size_t) sizeof(double)); printf("array size %lli \n", asize); data[0]=0.0; data[1]=1.0; while (i<asize) { data[i]=data[i-1]+1.0; ++i; } printf("%lf\n", (double) data[asize-1]); printf("success\n"); exit(exit_success); } double 8 bytes array size 1342177280 1342177279.000000 success
Comments
Post a Comment