1
votes

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;
        }
    }
}
2
If you run this under your platform debugger (gdb, whatever) you will likely be told immediately what is causing the seg-fault, which from this code is likely the only thing that is referencing a raw pointer: the FILE *fp and your assignment, rather than evaluation-check, to NULL. - WhozCraig
-1 I just peeked 3 random questions that are marked as related, and found in all of them suggestions to use a debugger or run through valgrind. This clearly indicate that you didn't look around that much. - Massimiliano

2 Answers

8
votes

Compile with warnings

if (fp = NULL)
5
votes
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;
}