+-

我正在写一个程序作为学校的项目,但我一直遇到 "Critical error detected c0000374 "或"...has triggered breakpoint",我试着调试,但没有成功,我也注意到有时它会运行,但有时它会在随机的malloc上崩溃。下面是我的代码,它应该为MOVIES生成链接列表,为每部电影生成ACTORS的链接列表。我对C语言没什么经验,请大家帮忙。
typedef struct meno {
char meno[100];
char priezvisko[100];
}NAME;
typedef struct herec {
struct meno meno;
int rok_narodenia;
struct herec *dalsi;
}ACTOR;
typedef struct film {
char meno[100];
struct herec *herec;
int rok_vyroby;
struct meno meno_rezisera;
struct film *dalsi;
}MOVIE;
MOVIE* nacitaj() {
FILE* file;
int i = 1;
file = fopen("filmy.txt", "r");
if (file == NULL) {
printf("SUBOR SA NEPODARILO OTVORIT");
return NULL;
}
MOVIE* film = malloc(sizeof(MOVIE*));
MOVIE* head = film;
MOVIE* film_temp = NULL;
ACTOR* herec = NULL;
ACTOR* herec_temp = NULL;
char temp,temp2;
film->dalsi = NULL;
while ((temp = fgetc(file)) != EOF) {
if (temp != '*') {
//pre film
if (film->dalsi != NULL) {
herec->dalsi = NULL;
herec = NULL;
herec_temp = NULL;
film = film->dalsi;
film_temp = NULL;
}
if(film_temp == NULL){
film_temp = malloc(sizeof(MOVIE*));
film->dalsi = (MOVIE*)film_temp;
}
film->meno[0] = temp;
while ((temp = fgetc(file)) != '\n') {
film->meno[i] = temp;
i++;
}
i = 1;
fscanf(file, "%d\n%s %s\n", &film->rok_vyroby, film->meno_rezisera.meno, film->meno_rezisera.priezvisko);
herec = (ACTOR*)malloc(sizeof(ACTOR*));
film->herec = (ACTOR*)herec;
}
if (temp == '*') {
//pre herca
if (herec != NULL && herec->dalsi != NULL) {
herec = (ACTOR*)herec->dalsi;
herec_temp = NULL;
}
if (herec_temp == NULL) {
herec_temp = malloc(sizeof(ACTOR*));
herec->dalsi = (ACTOR*)herec_temp;
}
fscanf(file, "%s %s %d\n", herec->meno.meno, herec->meno.priezvisko, &herec->rok_narodenia);
}
}
film->dalsi = NULL;
fclose(file);
return head;
}
3
投票
投票
malloc(sizeof(MOVIE*)); 是错误的,因为你只分配了指针大小的字节,而不是结构的大小。
然后你对结构的字段进行了反引用--所以你访问了不属于你的内存。
你需要按照结构体的要求分配尽可能多的字节。
malloc(sizeof(MOVIE));
或在这个特定的地方 - 但你在你的代码的其他地方也有同样的错误。
MOVIE* film = malloc(sizeof(film*));
第二种方法(用sizeof代替type)被认为是更好的方法,因为你可以在不改变sizeofs的类型的情况下改变对象的类型。
2
投票
投票
你的malloc应该是:
MOVIE* film = malloc(sizeof(MOVIE));
sizeof(数据结构),而不是指针。