2013-09-30 104 views
0

在我的代碼中,我的fscanf函數在第44行出現seg錯誤,我希望有人能告訴我爲什麼它不滿意這個,在此先感謝任何幫助。我已經通過gdb運行它,當我一行一行的時候,它在我的main中的fscanf上運行。seg fault merge sort porgram

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

回答

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