i trying initialize 2d array values keep encountering segmentation fault...i noticed occurred when added fscanf line of code...but don't understand what's wrong since understanding should work...this code snippet:
file * fp; int count, i,j; int **arr; arr = (int**)malloc(sizeof(int*)*9); for(i = 0; < 9; i++){ arr[i] = (int*)malloc(sizeof(int)*9); } fp = fopen("input.txt", "r"); for(i = 0; < 9; i++){ for(j = 0; j < 9; j++){ fscanf(fp, "%d", &arr[i][j]); } }
in code, neither
- checked sucess of
malloc()
- checked success of
fopen()
.
for of cases,
if
malloc()
fails, return null , using pointer cause undefined behaviour.if
fopen()
fails, return null, , using file pointer later again cause undefined behaviour.
put chcek sucess of library functions (in general) , use return value if successful.