segfault合并排序程序

时间:2013-09-30 01:17:15

标签: c merge segmentation-fault

我在第44行使用我的fscanf函数在我的代码中遇到了一个seg错误,我希望有人可以告诉我为什么对此不满意,提前感谢任何帮助。我通过gdb运行它,当我逐行浏览时,它会在我主要的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);
    }
}

1 个答案:

答案 0 :(得分:2)

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

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