使用 fscanf 读取分段错误

Reading with fscanf segmentation fault

我目前正在尝试用值初始化一个二维数组,但一直遇到分段错误...我注意到它总是在我添加 fscanf 代码行时发生...但我不明白有什么问题它因为根据我的理解它应该工作......这是一个代码片段:

    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]);
            }
        }

在你的代码中,你既不

  • 已检查 malloc()
  • 是否成功
  • 检查 fopen() 是否成功。

对于任何一种情况,

  1. 如果 malloc() 失败,它将 return NULL 并且使用该指针将导致 undefined behaviour.

  2. 如果fopen()失败,会returnNULL,后面使用文件指针会再次导致undefined behaviour.

检查所有库函数是否成功(通常),只有在成功时才使用 return 值。