Aakash Anuj
Aakash Anuj

Reputation: 3871

Segmentation fault - Unknown reason

I am getting segmentation fault with this code even though the two files are having 2^14 values each. Could anyone tell me the reason why.

#define N 128
#include<stdio.h>
#include <malloc.h>
int A[N][N];
int B[N][N];
int C[N][N];
void mmul();

int main()
{
    int p,q;
    FILE *fp;
    fp=fopen("A.txt","r");
    if(fp=NULL)
        printf("Error\n");
    printf("A");
    for(p=0;p<(1<<7);p++)
    {
        for(q=0;q<(1<<7);q++)
        {
            fscanf(fp, "%d", &A[p][q]);
        }
    }
    fclose(fp);
    fp=fopen("B.txt","r");
    if(fp=NULL)
        printf("Error\n");
    for(p=0;p<(1<<7);p++)
    {
        for(q=0;q<(1<<7);q++)
        {
            fscanf(fp, "%d", &B[p][q]);
        }
    }
    fclose(fp);
    printf("here");
    mmul();
}

void mmul()
{
    int i,j,k;
    unsigned int sum;
    for(i=0;i<N;i++)
    {
        for(j=0;j<N;j++)
        {
            sum=0;
            for(k=0;k<N;k++)
            {
                sum=sum+(A[i][k]*B[k][j]);
            }
            C[i][j]=sum;
        }
    }
}

Upvotes: 1

Views: 218

Answers (2)

Dmytro Sirenko
Dmytro Sirenko

Reputation: 5083

if(fp=NULL)
printf("Error\n");`
  • it is the whole if body. So if there is no file, you'll get a NULL fp, print "Error" and continue the execution with NULL fp. It causes the segmentation faults.

Also, it is an assignment, not a comparison, so you always get NULL fp, not printing the error.

You need to add exit statement:

if (fp == NULL) {
   fprintf(stderr, "Error: failed to open file\n");
   return -1;
}

Upvotes: 5

David Ranieri
David Ranieri

Reputation: 41045

Compile with warnings

if (fp = NULL)

Upvotes: 8

Related Questions