0

我正在尝试使用头文件编写一个程序来处理分配的列表和文件,但是我遇到了标题中提到的错误。该错误发生在第三次 addNode 运行 (addNode(l, r3);) 时,程序崩溃。我一直在试图找出可能导致它近 2 小时的原因,但一无所获。

主.c:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "file.h"
#include "list.h"

int main(){
    int i;
    list l;
    l = initList();
    node r1, r2, r3, r4, curNode;
    r1 = malloc(sizeof(struct nodeR));
    r2 = malloc(sizeof(struct nodeR));
    r3 = malloc(sizeof(struct nodeR));
    r4 = malloc(sizeof(struct nodeR));

    strcpy(r1->payload, "test1");
    strcpy(r2->payload, "test2");
    strcpy(r3->payload, "test3");
    strcpy(r4->payload, "test4");

    addNode(l, r1);
    addNode(l, r2);
    addNode(l, r3);
    addNode(l, r4);

    curNode = l->head;
    for (i = 1; i < l->length; i++){
        printf("%s\n", curNode->payload);
        curNode = curNode->next;
    }

    reverseList(l);

    curNode = l->head;
    for (i = 1; i < l->length; i++){
        printf("%s\n", curNode->payload);
        curNode = curNode->next;
    }

}

列表.h:

#ifndef LIST_H_
#define LIST_H_

#define TRUE 1
#define FALSE 0
typedef struct nodeR* node;
struct nodeR{
    char payload[20];
    node next;
    node previous;
};
typedef struct listR* list;
struct listR{
    node head;
    node tail;
    int length;
};
list initList(); //creates a new list and returns it. Returns NULL if it fails
int destroyList(list l); //frees memory from the list. Returns TRUE upon success or FALSE upon failure
int getNodeIndex(list l, node targetNode); //returns the position of the targetNode in the list. Returns a negative number if it fails
int getListLength(list l); //returns the length of the list. Returns a negative number if it fails
int addNode(list l, node newNode); //adds newNode at the end of the list. Returns TRUE upon success or FALSE upon failure
int insertNodeBefore(list l, node targetNode, node newNode); //injects newNode in the list right before the targetNode. Returns TRUE upon success or FALSE upon failure
int deleteNode(list l, node targetNode); //deletes targetNode from list. Returns TRUE upon success or FALSE upon failure
list reverseList(list l); //returns a list which is created by reversing the order of the elements of l. Returns NULL if it fails

#endif

list.c 中的 addNode

int addNode(list l, node newNode){
list temp;
if (l == NULL){     
    printf("Error: List does not exist or has already been destroyed.");
    return FALSE;
}

if (getListLength(l) == 0){ 
    l->head = newNode;
    l->tail = newNode;
    l->length++;
}
else {              
    l->tail->next = newNode;
    newNode->previous = l->tail;
    l->tail = newNode;
    l->length++;
}
return TRUE;

}

注意:a)头文件是教授给的,赋值给代码list.c b)实际代码比较大,据我所知和问题无关,所以选择只贴有问题的函数. c) main.c 只是一个测试程序,旨在测试我的代码是否正常工作。也就是说,它是我写的,而不是教授,所以问题可能出在那个地方。d) 正如我上面所说,崩溃发生在第三次 addNode 运行期间,对于节点 r3。

在此先感谢您的帮助。

4

0 回答 0