Reputation: 43
Im getting a seg fault in my code at line 44 with my fscanf function and i was hoping someone can tell my why it is not happy with this, thanks in advance for any help. I've ran it through gdb and when i went through line by line it trips up at the fscanf in my main.
#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);
}
}
Upvotes: 0
Views: 105
Reputation: 7056
Your variable i
is not initialized in the statement where the seg fault happens.
int i, k = 0;
int array1[num];
while(!feof(fp))
{
// i is not initliazed here
fscanf(fp, "%d", &array1[i]); //SEG FAULT HERE
i++;
}
You probably want to initialize it to zero:
int i = 0, k = 0;
Also, you really need to make sure num
is initialized when this statement is executed:
int array1[num];
Upvotes: 2