具有C语言function的realloc结构

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

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

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

/* John Maynard 1000916794 7/15/2013 HW-06 */ #include  #include  #include  #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; } 

realloc()可能会返回一个与原始指针不同的指针,但是你只能将它指定给temp这样调用函数之后仍然可以使用原始指针。 更改double_array_size()以返回realloc()返回的新指针并调用

 d = double_array_size(d, array_size); 

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

结合Ingo和codroipo的答案,你必须从double_array_size返回新指针,或者你必须传入指向d的指针,这样你就可以从double_array_size更新指针

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

 void double_array_size(struct course** d, int new_size){ *d = realloc(*d, new_size * sizeof(struct course)); . . . }