0

我的 C 程序崩溃了,我太新了,无法弄清楚。到目前为止它非常简单,我想代码足以找出问题所在。

我只是想逐行读取文件。一旦内存不足,我会将结构的内存加倍。如果这还不够信息,我会提供您需要的任何其他信息。

非常感谢您的帮助,因为我已经被困了好几个小时了。

/*
John Maynard
1000916794
7/15/2013
HW-06
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define N 100

struct course
{
   char subject[11];
   int catalogNum;
   int sectionNum;
   int enrollmentTotal;
   int enrollmentCap;
};

void readFile(struct course *d, char* filename);

void double_array_size(struct course *d, int new_size);

int main(void)
{
   char *filename = "hw06-data.csv";
   struct course *d;

   d = malloc( N * sizeof(struct course));

   readFile(d, filename);

}


void readFile(struct course *d, char* filename)
{
   FILE* fp;
   char buffer[100];
   int i = 0, array_size = 100;
   struct course *temp;


   if( ( fp = fopen(filename, "r") ) == NULL)
   {
      printf("Unabale to open %s.\n", filename);
      exit(1);
   }

   fgets(buffer, sizeof(buffer), fp);

   while( fgets(buffer, sizeof(buffer), fp) != NULL)
   {
      if (i == array_size)
      {
         array_size *= 2;
         double_array_size(d, array_size);
         printf("reached limit...increasing array to %d structures\n", array_size);
      }



      i++;
   }
   fclose( fp );
}

void double_array_size(struct course *d, int new_size)
{
   struct course *temp;

   temp = realloc(d, new_size * sizeof(struct course));

   if(temp == NULL)
   {
      printf("unable to reallocate\n");
      exit(1);
   }

   else
      d = temp;
}
4

3 回答 3

2

realloc()可能会返回与原始指针不同的指针,但您将其分配给temp只有这样调用函数才能在之后使用原始指针。更改double_array_size()为返回返回的新指针realloc()并调用

d = double_array_size(d, array_size);

此外,您应该始终检查结果 fo等。如果没有更多可用内存,它们可能会返回malloc()NULLrealloc()

于 2013-07-16T15:05:20.900 回答
0

结合 Ingo 和 codroipo 的答案,您必须返回新指针 from double_array_size,或者您必须传入一个指针,d以便您可以从double_array_size

于 2013-07-16T15:15:46.030 回答
0

realloc会重新分配内存,所以可能d指向的内存会被释放,所以double_array_size要编辑d,你可以试试:

void double_array_size(struct course** d, int new_size){
*d = realloc(*d, new_size * sizeof(struct course));
.
.
.
}
于 2013-07-16T15:10:42.160 回答