Search code examples
c++windowsmemoryallocation

Memory allocation problem C/Cpp Windows critical error


I have a code that need to be "translated" from C to Cpp, and i cant understand, where's a problem. There is the part, where it crashes (windows critical error send/dontSend):

 nDim = sizeMax*(sizeMax+1)/2;
 printf("nDim  = %d sizeMax = %d\n",nDim,sizeMax);
 hamilt = (double*)malloc(nDim*sizeof(double));
 printf("End hamilt alloc. %d allocated\n",(nDim*sizeof(double)));
 transProb = (double*)malloc(sizeMax*sizeMax*sizeof(double));
 printf("End transProb alloc. %d allocated\n",(sizeMax*sizeMax*sizeof(double)));
 eValues = (double*)malloc(sizeMax*sizeof(double));
 printf("eValues allocated. %d allocated\n",(sizeMax*sizeof(double)));
    eVectors  = (double**)malloc(sizeMax*sizeof(double*));
 printf("eVectors allocated. %d allocated\n",(sizeMax*sizeof(double*)));
 if(eVectors) for(i=0;i<sizeMax;i++) {
                 eVectors[i] = (double*)malloc(sizeMax*sizeof(double));
                 printf("eVectors %d-th element allocated. %d allocated\n",i,(sizeMax*sizeof(double)));
                 }
 eValuesPrev = (double*)malloc(sizeMax*sizeof(double));
 printf("eValuesPrev allocated. %d allocated\n",(sizeMax*sizeof(double)));
 eVectorsPrev  = (double**)malloc(sizeMax*sizeof(double*));
 printf("eVectorsPrev allocated. %d allocated\n",(sizeMax*sizeof(double*)));
 if(eVectorsPrev) for(i=0;i<sizeMax;i++) {
                     eVectorsPrev[i] = (double*)malloc(sizeMax*sizeof(double));
                     printf("eVectorsPrev %d-th element allocated. %d allocated\n",i,(sizeMax*sizeof(double)));
                     }

Log:

nDim  = 2485 sizeMax = 70
End hamilt alloc. 19880 allocated
End transProb alloc. 39200 allocated
eValues allocated. 560 allocated
eVectors allocated. 280 allocated 

So it crashes at the start of the loop of allocation. If i delete this loop it crashes at the next line of allocation. Does it mean that with the numbers like this i have not enough memory??

Thank you.


Solution

  • On my machine, this program compiles, executes without error and reports no memory problems when run through valgrind. Unless you are running on a small embedded system, your problem is likely something external to this code, because the total amount of memory allocated by this program is less than 140 KiB.

    Besides, when malloc fails, it doesn't crash, it returns NULL. This code properly checks for eVectorsPrev being NULL, so there should be no NULL dereferencing problems here.