EsraaEid
EsraaEid

Reputation: 25

Why does this code give me a segmentation fault?

I am trying to generate 2 matrices to multiply them later, but my code doesn't work! It gives me "segmentation fault 'core dumped'"

Here is my code:

double *c;
void populate(int size,double *a,double *b)
{
    int i,j;
    for(i=0;i<size;i++)
    {
        for(j=0;j<size;j++)
        {
            *(a+i*size+j)=1+rand()%100;
            *(b+i*size+j)=1+rand()%100;
        }
    }
}
int main(int argc , char *argv[])
{
    if(argc!=2)
    {
        fprintf(stderr,"You must Enter (..M..)for the size of M*M Matrix ,, try again\n");
        exit(-1);
    }

    if (atoi(argv[1]) <= 0) {
        fprintf(stderr, "%d must be > 0\n", atoi(argv[1]));
        return -1;
    }

    const int M=atoi(argv[1]); // size M*M

    double *a;
    double *b;
    populate(M,a,b);
    return 0;
}

Upvotes: 0

Views: 61

Answers (2)

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

Because you never allocate space for a or b.

As they are, a and b don't point to valid memory, when you try to write to wherever they point you are apparently accessing memory that is illegal to your program, hence causing a Segmentation Fault.

Try this

double *a;
double *b;

a = malloc(M * M * sizeof(double));
if (a == NULL)
    return -1;
b = malloc(M * M * sizeof(double));
if (b == NULL)
{
    free(a);
    return -1;
}
populate(M, a, b);

and mixing declarations with code in c, makes the code look ugly.

Upvotes: 3

chqrlie
chqrlie

Reputation: 144540

You need to allocate these matrices:

double *a = calloc(M * M, sizeof(double));
double *b = calloc(M * M, sizeof(double));
if (a == NULL || b == NULL) {
    fprintf(stderr, "Not enough memory for %d x %d matrices\n", M, M);
    exit(1);
}
populate(M,a,b);

Upvotes: 4

Related Questions