在我正在创建的这个 C 程序中,我在运行时得到一个 STATUS_ACCESS_VIOLATION,我相信这是由于一次初始化所有结构,然后使用 malloc() 来增加它们的大小,导致指向已在使用中的引用内存的指针。这是发生此异常的函数:
void process_track(char filename[], struct track *tracks) {
int i = 0;
FILE* fp;
int lines;
lines = count_file_lines(filename);
tracks = malloc(lines);
fp = fopen(filename, "r");
if (fp == NULL) {
printf("\n\"%s\" File not found", filename);
exit(1);
} else {
for (i = 0; i < lines; i++) {
fscanf(fp, "%d %d %d %d\n", &tracks[i].number, &tracks[i].startnode, &tracks[i].endnode, &tracks[i].minutes);
}
for (i = 0; i < lines; i++) {
printf("%d ", tracks[i].number);
printf("%d ", tracks[i].startnode);
printf("%d ", tracks[i].endnode);
printf("%d\n", tracks[i].minutes);
}
}
}
具体来说,它发生在以下行:
fscanf(fp, "%d %d %d %d\n", &tracks[i].number, &tracks[i].startnode, &tracks[i].endnode, &tracks[i].minutes);
该函数在以下函数中调用(案例 3):
void get_file(char textfilename[], int optnumber) {
struct node *nodes;
struct track *tracks;
struct course *courses;
struct entrant *entrants;
struct checkpointdata *checkpointdatas;
char filename[20]; //Array of char for filename
printf("Enter the name of the %s text file(with file extension) :", textfilename);
scanf(" %[a-zA-Z._1-9]", &filename);
switch (optnumber) {
case 1:
process_name(filename);
break;
case 2:
process_node(filename, nodes);
break;
case 3:
process_track(filename, tracks);
break;
case 4:
process_course(filename, courses);
break;
case 5:
process_entrant(filename, entrants);
break;
case 6:
process_checkpointdata(filename, checkpointdatas);
break;
}
}
它读第一行很好,但在那之后失败了。由于其他“process_[data]”非常相似,我也尝试了这些。有些可以正常工作,有些也会出现异常,有些会在输出时检索垃圾。
我将如何解决这个问题,或者分配内存以便它不会与预先分配的内存冲突(如果这确实是问题)?