我正在创建的这个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]”非常相似,我也试过了。有些可以正常工作,有些也会提出异常,有些会在输出时检索垃圾。
我将如何解决这个问题,或者分配内存以使其不与预先分配的内存发生冲突(如果这确实是问题)?