C:链接列表访问内存不良

时间:2015-12-15 11:53:10

标签: c memory-management struct linked-list exc-bad-access

我必须处理链接列表,即使在我的主要事件发生之前,也会遇到错误的访问错误。我不知道什么是错的。我对动态内存管理比较陌生。如果有人可以看一下这些功能会很好。该声明由教授提供,因此我们必须返回DoubleNote *。 我的代码如下:

#include <stdio.h>
#include <stdlib.h>

typedef struct node{

    double var;

    struct node *next;


} DoubleNode;


DoubleNode* insertFirst(DoubleNode* head, double d){

    DoubleNode* new_head;
    new_head = (DoubleNode*)malloc(sizeof(DoubleNode));

    if (new_head == NULL) {
        printf("Error: Allocating memory for new node failed!");
        exit(1);
    }

    new_head->var = d;

    new_head->next = head;

    head = new_head;


    return head;

}



DoubleNode* inserLast(DoubleNode* head, double d){

    DoubleNode* current = head;

    while (current != NULL) {
        current = current->next;
    }

    current->next = (DoubleNode*)malloc(sizeof(DoubleNode));
    if (current->next == NULL) {
        printf("Error: Allocating memory for new node failed!");
        exit(1);
    }
    current->next->var = d;
    current->next->next = NULL;

    return head;

}

DoubleNode* inverseDoubleListCon(DoubleNode* head){

    DoubleNode* current = head; // iteration variable starts on head of old list
    DoubleNode* conHead = current; // Head of the new list

    while (current != NULL) {

        current = current->next; //iteration step

        DoubleNode* newConHead = (DoubleNode*)malloc(sizeof(DoubleNode)); //allocating memory for new head

        if (newConHead == NULL) {
            printf("Error: Allocating memory for new node failed!");
            exit(1);
        }

        newConHead = current; // new_head is the next variable in the old list

        newConHead->next = conHead; //new head points to old head of the new list

        conHead = newConHead; // new head is set
    }


    return conHead;

}

void printList(DoubleNode* head){

    DoubleNode* current = head;

    while (current != NULL) {
        printf("%lf\n", current->var);
        current = current->next;
    }

}




int main(){

    DoubleNode* head = NULL;
    DoubleNode* inverseHead = NULL;
    double d;
    int i;
    int sizeOfList;

    printf("Insert amount of variables: \n");
    scanf("%d", &sizeOfList);

    for (i = 0; i < sizeOfList; i++) {
        printf("Insert variable for node [%d]: \n", i);
        scanf("%lf", &d);

        head = insertFirst(head, d);
    }

    printList(head);

    inverseHead = inverseDoubleListCon(head);

    printList(inverseHead);



    return 0;
}

1 个答案:

答案 0 :(得分:1)

首先,sizeOfList未被初始化。您需要添加代码以从用户获取大小的值。

您也没有从insertFirst函数更新头指针的值。下面的代码应该有所帮助。

DoubleNode* head= NULL;

// Code to get the value of sizeofList

for (i = 0; i < sizeOfList; i++)
{
   ...
    head = insertFirst(head, d);
}

反向功能过于复杂。您正在newConHead中分配内存,这对于反转链接列表不是必需的。

我建议改写How to reverse a singly linked list using only two pointers?http://www.geeksforgeeks.org/write-a-function-to-reverse-the-nodes-of-a-linked-list/