-1

I am currently trying to initialize a 2d array with values but keep encountering a segmentation fault...I noticed it always occurred when I added the fscanf line of code...but I don't understand what's wrong with it since from my understanding it should work...this is a code snippet:

    FILE * fp;
        int count, i,j;
        int **arr;

        arr = (int**)malloc(sizeof(int*)*9);
        for(i = 0; i < 9; i++){
            arr[i] = (int*)malloc(sizeof(int)*9);
        }    

fp = fopen("input.txt", "r");

    for(i = 0; i < 9; i++){
            for(j = 0; j < 9; j++){
                fscanf(fp, "%d", &arr[i][j]);
            }
        }
user3580218
  • 121
  • 1
  • 13

1 Answers1

1

In your code, you neither

  • checked for the sucess of malloc()
  • checked for the success of fopen().

For any of the cases,

  1. if malloc() fails, it will return NULL and using that pointer will cause undefined behaviour.

  2. if fopen() fails, it will return NULL, and using the file pointer later will again cause undefined behaviour.

Put a chcek for sucess of all the library functions (in general) and use the return value only if they are successful.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • apparently fp is showing up as null...though I do have a file on the same directory named input.txt – user3580218 Apr 28 '15 at 08:22
  • In the case of the 2d array I tried initializing the value of the 2d array I made and it did print out the values so it is not null...Also I just figured out that the name of the file was the problem...It should be "input" not "input.txt"...I did not need to add a file extension...my mistake sorry – user3580218 Apr 28 '15 at 08:31