cipper
cipper

Reputation: 287

calloc initializes more memory than available

This is the piece of code. With N=70000 or more, the code proceeds to STEP1 and crashes with Segmentation Fault. Instead, if i put e.g. N=50000, calloc returns NULL and the program exits returning 2. So why with N=70000 calloc does not complain? I've compiled this with both gcc and icc.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>

int main(){

    float *matrix1,*q,*matrix2;
    int i,j,n,N=70000;
    n = N+1;
    if( (q=calloc(n,sizeof*q)) == NULL ) return 1;
    if( (matrix1=calloc(n*n,sizeof*matrix1)) == NULL ) return 2;
    if( (matrix2=calloc(N*N,sizeof*matrix2)) == NULL ) return 3;

    //STEP1
    for(i=0;i<N;i++){
        for(j=0;j<N;j++){
            matrix2[i*N+j] = i*N+j;
        }
    }

    //STEP2
    for(i=0;i<N;i++){  // raw
        for(j=0;j<=i;j++){ // column
            if(i==j){ matrix1[i+j*n] = 0; } //diagonal elements
            else {
                matrix1[i+j*n] = i+j*n;
                matrix1[j+i*n] = j+i*n;
            }
        }
    }

    return 0;
}

Upvotes: 1

Views: 135

Answers (1)

glglgl
glglgl

Reputation: 91109

You are exceeding the allowable value range for some variables.

You have int N=70000. A N*N gives you an int as well, which overflows and gets 605032704 instead, a value which can perfectly be allocated on your system.

You should use size_t for calling calloc(). In this case, it is probably large enough for your system even if you have 64 bits.

Of course, even size_t might overflow, and, depending on your system, quite early. So you should take care not to exceed SIZE_MAX when assigning.

Upvotes: 4

Related Questions