错误 - C

时间:2015-06-18 11:13:09

标签: c double-free

我正在尝试使用头文件编写程序来处理分配的列表和文件,但是我在标题中提到的错误方面遇到了问题。第3次addNode运行时发生错误(addNode(l,r3);),程序崩溃。我现在一直试图找出可能导致它近2个小时的原因,并且什么都没有。

main.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;
    }

}

list.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)如上所述,崩溃发生在第3次addNode运行期间,对于节点r3。

提前感谢您的帮助。

0 个答案:

没有答案