我是C新手,无所适从。几个小时我一直在撞墙。将节点添加到链接列表时发生堆损坏
我创建了两个struct
s来保存我的链表节点。第一个,struct movie
显然拥有电影。第二个struct actor
是将演员节点添加到电影节点。
struct movie {
struct movie* next;
struct actor* actors;
char name[100];
int rating;
genre type;
} *list = NULL;
// contains actor information
struct actor {
struct actor* next;
char name[100];
};
麻烦的是当我尝试将actor
添加到movie
。
int add_actor(char* movie_name, char* actor_name)
{
struct movie *tmp = list, *tmpList = NULL;
struct actor *tmpActor = NULL, *current = NULL;
//check if movie name exists in list
while (tmp != NULL) {
if (strcmp(tmp->name, movie_name) == 0) {
tmpList = tmp;
}
tmp = tmp->next;
} //make sure newActor->next is pointing to the correct place
if (tmpList == NULL) { return 0; } //if movie in not in list, return 0
//The problem occurs most often at this line, with the exception below.
//Exception thrown at 0x77433500 (ntdll.dll) in hw7.exe: 0xC0000005: Access violation reading location 0x006F4E42
struct actor *newActor = (struct actor*)malloc(sizeof(struct actor));//create new actor node
if (tmpList->actors == NULL){ //if the movie has no actors in list
tmpList->actors = newActor;
strcpy(newActor->name, actor_name);
newActor->next = NULL;
return 1;
}
else { //check if actor name already exists in list
while (tmpActor != NULL) {
if (strcmp(tmpActor->name, actor_name) == 0) {
return -1; //if actor already exists return -1
}
tmpActor = tmpActor->next;
}
tmpActor = tmp->actors;
//insert at beginning of list
if (strcmp(actor_name, tmpActor->name) >= 0) {
newActor->next = tmpActor;
tmpActor = newActor;
return 1;
}
//insert actor in arbitrary position
while (tmpActor != NULL && strcmp(actor_name, tmpActor->name)<0) {
current = tmpActor;
tmpActor = tmpActor->next;
}
newActor->next = current->next;
strcpy(newActor->name, actor_name);
current->next = newActor;
return 1;
}
}
至多我已经能够将两个演员添加到两个不同的电影。问题总是出现在第三项。
更新异常:
通过我的代码精心挑选后,我发现了一个明显的错误。当传递大于几个字符的内容时,程序会崩溃。当我声明传递给add_actor
函数的指针变量movie_name
和actor_name
时,我没有为较大的名称分配足够的空间。
char* movie_name = (char*)malloc(sizeof(char*));
char* actor_name = (char*)malloc(sizeof(char*));
变化后:
char* movie_name = (char*)malloc(5000*sizeof(char*));
char* actor_name = (char*)malloc(5000*sizeof(char*));
我能添加的电影和演员没有崩溃。
就目前来看,这是很多需要经历的代码。你可能[编辑]并将其折叠到[MCVE](http://stackoverflow.com/help/mcve)?谢谢! – CodeMouse92
编辑完成,谢谢 – corporateWhore
建议阅读[如何调试小程序](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/)(再次)。创建此MCVE将导致在80%的案例中自己发现错误,并在剩下的情况下帮助其他人帮助:) –