我是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%的案例中自己發現錯誤,並在剩下的情況下幫助其他人幫助:) –