c - Can malloc be relied on to return contiguous memory, and how do I properly call it? -


before started, yes have read a possible duplicate, malloc being weird in linux, cplusplus.com on malloc , done searching on google.

i have scientific computing problem requires large 2d array. i'm following code found in copy of "numerical recipes in c", , having problem unallocated memory in middle of 2d array. working in windows, , using c++ msvc 2012.

here 2d array allocation

  unsigned long nrl=0;   unsigned long nrh=749774;   unsigned long ncl=0   unsigned long nch=250657;   unsigned long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;   double **m;   if((size_t)(nrow*ncol)<(size_t)nrow){     m=null;     return m;   }   /*allocate pointers rows*/   m=(double **)malloc((size_t)(nrow)*sizeof(double*));   if (!m){     m=null;     return m;   }    /*allocate rows , set pointers them*/   m[nrl]=(double *) malloc((size_t)((nrow*ncol)*sizeof(double)));   if(!m[nrl]){       free(m[nrl]);     free(m);     m=null;     return m;   }   for(i=nrl+1;i<=nrh;i++)m[i]=m[i-1]+ncol;   /*the 2d array should callable m[nrow][ncol]*/   /*pseudo-code below*/   m[0][0] == good, allocated memory   m[125][200923] == unallocated, crashes program   m[nrh-1][nch-1] == good, allocated memory 

i relying on malloc return null if memory allocation fails (i null values if try allocate very large arrays.

also, have attempted double *m = new double[nch*nrh], gives me memory allocation error. open suggestions alternative implementations, need able know whether allocation works , reallocate smaller block if necessary.

edit:

this c function, majority of code in c++.

update:

thanks david, able fix problem. changing overflow check

if((size_t)(nrow*ncol)<(size_t)nrow) 

to

if(size_max/nrow < ncol || size_max/ncol < nrow || nrow*ncol<nrow) 

allows malloc fail when should.

i'm guessing have 32 bit process. note nrow*ncol*sizeof(double) (a lot!) greater 2^32. attempting allocate 1400 gb, rather imagine comes surprise you.

it's not possible allocate memory, , not in 32 bit process. code appears run because (nrow*ncol)*sizeof(double) suffers integer overflow , call malloc succeeds doesn't allocate memory expect to. in fact, in 64 bit process have overflow, because nrow*ncol evaluated 32 bit arithmetic because declared nrow , ncol unsigned long. should size_t.

anyway, going need reconsider entire approach problem. can expect useful 1400 gb dense matrix?


Comments

Popular posts from this blog

php - Submit Form Data without Reloading page -

linux - Rails running on virtual machine in Windows -

php - $params->set Array between square bracket -