0

我的 fscanf 函数在第 44 行的代码中出现了段错误,我希望有人能告诉我为什么对此不满意,在此先感谢您的帮助。我已经通过 gdb 运行它,当我逐行运行时,它在我的 main 中的 fscanf 处跳闸。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <errno.h>   // for errno
#include <limits.h>  // for INT_MAX

void mergeSort(int a[], int low, int high);
void merge(int a[], int low, int mid, int high);

int main(int argc, char** argv)
{
    if(argc != 3){
      printf("Incorrect number of arguments\n");
      printf("Please enter a.out, # of numbers, and input file\n");
      return 1;
   }

   FILE* fp = fopen(argv[2], "r");

   char *p;
   int num;
   errno = 0;

   int conv = strtol(argv[1], &p, 10);

   // Check for errors: e.g., the string does not represent an integer
   // or the integer is larger than int
   if (errno != 0 || *p != '\0' || conv > INT_MAX) {
        // Put here the handling of the error, like exiting the program with
        // an error message
    } 
    else {
    // No error
    num = conv;
    }

   int i, k = 0;

   int array1[num];

   while(!feof(fp))
   {
        fscanf(fp, "%d", &array1[i]); //SEG FAULT HERE
        i++;
   }

   mergeSort(array1, 0, num);

   for(k = 0; k < num; k++)
   {
        printf("%d\n", array1[k]);
   }

   return 0;
}

void merge(int a[], int low, int mid, int high)
{
    int b[10000];
    int i = low, j = mid + 1, k = 0;

    while (i <= mid && j <= high) {
        if (a[i] <= a[j])
            b[k++] = a[i++];
        else
            b[k++] = a[j++];
    }
    while (i <= mid)
        b[k++] = a[i++];

    while (j <= high)
        b[k++] = a[j++];

    k--;
    while (k >= 0) {
        a[low + k] = b[k];
        k--;
    }
}

void mergeSort(int a[], int low, int high)
{
    if (low < high) {
        int m = (high + low)/2;
        mergeSort(a, low, m);
        mergeSort(a, m + 1, high);
        merge(a, low, m, high);
    }
}
4

1 回答 1

2

您的变量i未在发生段错误的语句中初始化。

   int i, k = 0;

   int array1[num];

   while(!feof(fp))
   {
        // i is not initliazed here
        fscanf(fp, "%d", &array1[i]); //SEG FAULT HERE
        i++;
   }

您可能希望将其初始化为零:

   int i = 0, k = 0;

此外,您确实需要确保num在执行此语句时已初始化:

   int array1[num];
于 2013-09-30T01:20:31.837 回答