WHILE循环中的分段错误

时间:2014-02-04 02:05:54

标签: c arrays segmentation-fault

我正在尝试读取包含整数的文本文件,并将它们放入数组中。创建数组后,我将对它们进行排序。但是,我试图确保在实现它们时工作正常但在尝试打开文件时遇到分段错误。我不明白为什么。

#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <ctype.h>

#define SIZE_T_MAX 16777216

/****** FORWARD DECLARATIONS ******/
void die(const char *message) {
  if(errno) {
    perror(message);
  } else {
    printf("ERROR: %s\n", message);
  }

  exit(1);
}

// ARRAY
typedef struct int_array {
  int *array;
  size_t length;
  size_t capacity;
} int_array;

void int_array_init(int_array *array);
void int_array_free(int_array *array);
void int_array_add(int_array *array, int value);
/****** END OF DECLARATIONS  ******/
//
//
/********** MAIN PROGRAM **********/
int main(char argc, char *argv[]) {
  // VARIABLES
  FILE *data;
  int_array numbers;
  int_array_init(&numbers);
  int i = 0;
  char value[10];

  // LOAD FILES
  printf("Loading files...\n");

  data = fopen("list0.txt", "r");
  if(data == NULL) die("Failed to load file.");

  while(!feof(data) && !ferror(data)) {
    fscanf(data, "%s", value);
    int_array_add(&numbers, atoi(value));
    printf("%d", numbers.array[i]);
    i++;
  }

  // CLEAN UP
  int_array_free(&numbers);
  fclose(data);

  return 0;
}
/*********** END OF MAIN **********/
//
//
/******* ADDITIONAL METHODS *******/
void int_array_init(int_array *array) {
  array->array = NULL;
  array->length = 0;
  array->capacity = 0;
}

void int_array_free(int_array *array) {
  free(array->array);
  array->array = NULL;
  array->length = 0;
  array->capacity = 0;
}

void int_array_add(int_array *array, int value) {
  if (array->length == array-> capacity)
  {
    int new_capacity;

    if (array->capacity == 0) new_capacity = 10;
    else new_capacity = array->capacity * 2;

    if (new_capacity > array->capacity && new_capacity < SIZE_T_MAX / sizeof(int)) {
      int *new_array = realloc(array->array, new_capacity * sizeof(int));
      if (new_array != NULL) {
        array->array = new_array;
        array->capacity = new_capacity;
      } else {
        die("Out of Memory");
      }
    } else {
      die("Overflow.");
    }
  }

  array->array[array->length] = value;
  array->length++;
}

1 个答案:

答案 0 :(得分:0)

我已更正并修正了我的代码。问题在于while循环是无限的,并用:

进行纠正
while(!feof(data) && !ferror(data))