1

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
  • 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. Commented Nov 9, 2012 at 16:31
  • -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. Commented Nov 9, 2012 at 16:35

2 Answers 2

8

Compile with warnings

if (fp = NULL) 
Sign up to request clarification or add additional context in comments.

Comments

5
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; } 

2 Comments

But the files are there . Then what is the problem
Oh yeah...got it !! Didnt look thorugh it carefully

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.