cmallocdefragmentation

malloc is failing to allocate memory


I'm writing a C Code to solve Euler equations. My code works perfectly fine on the cluster but not on my pc. Seems to be an issue with malloc(). It is not being able to allocate the requested memory and fails.

How do i make it work? is it something to do with Defragmentation? But the system settings show (0% Defragmented).

Just including a part of malloc() code here.

double **u, **rho_u, **rho,    
int Size = 1000;
u = (double**)malloc(Size*sizeof(double*));
for(i=0;i<=Size;i++)
    u[i] = (double*)malloc(Size*sizeof(double));

rho_u = (double**)malloc(Size*sizeof(double*));
for(i=0;i<=Size;i++)
    rho_u[i] = (double*)malloc(Size*sizeof(double));

Solution

  • You probably corrupt your heap here:

    for(i=0;i<=Size;i++)
        u[i] = (double*)malloc(Size*sizeof(double));
    

    You assign 1001 pointers, but only have 1000 allocated. Correct version:

    for(i=0;i<Size;i++)
        u[i] = (double*)malloc(Size*sizeof(double));
    

    Same for the second loop.