2013-05-03 81 views
1

我的代碼編譯正確,但在insertLast函數的4個循環後,程序崩潰。有人能幫我理解爲什麼嗎?鏈接列表 - 程序在添加節點時崩潰

我之前發佈了一個類似的問題,這幫助我識別了其他問題。我已經重寫了這個函數,但是我仍然遇到同樣的問題。下面我的代碼:

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


int main (int argc, char* argv[]) 

{ 
    int ii; 

     { 
     FILE* f; /*open file for reading to get ints*/ 
     f = fopen(argv[1], "r"); 

     if(f==NULL) 
      { 
      printf("Error: could not open file"); 
      return 0; 
      } 

    LinkedList* canQueue=createList(); 

    for(ii = 0; ii < 10; ii++) 
     { 
     TinCan* tempCan= (TinCan*) malloc(sizeof(TinCan)); 
     fscanf(f, " WGT_%d", &tempCan[ii].weight); 
     insertLast(canQueue, tempCan); /*Inserts the new can into linked list*/ 
     } 
    testLinkedList(canQueue); 
    } 
    return 0; 

} 

LinkedList.h

typedef struct TinCan 
    { 
    int weight; 
    } TinCan; 

typedef struct Node 
    { 
    TinCan* data; 
    struct Node *next; 
    } Node; 

typedef struct LinkedList 
    { 
    Node *head; 
    } LinkedList; 

void insertLast(LinkedList* list, TinCan *newData); 
LinkedList* createList(); 
void testLinkedList(LinkedList* list); 

LinkedList.c

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

LinkedList* createList() /*creates empty linked list*/ 
    { 
    LinkedList* myList; 
    myList = (LinkedList*)malloc(sizeof(LinkedList)); 
    myList->head = NULL; 
    return myList; 
    } 

void insertLast(LinkedList* list, TinCan *newData) 
    { 
    Node* newNode = (Node*)malloc(sizeof(Node)); 
    newNode->data = newData; 
    newNode->next = NULL; 

    if(list->head==NULL) 
     { 
     Node* current = (Node*)malloc(sizeof(Node)); 
     list->head=newNode; 
     current=newNode; 
     } 

     else 
      { 
      Node* temp = (Node*)malloc(sizeof(Node)); 
      temp = list->head; 
      while(temp->next!=NULL) 
       { 
       temp = temp->next; 
       } 
      temp->next = newNode; 
      } 
    printf("Looped\n"); 
    } 


void testLinkedList(LinkedList* list) 
    { 
    Node* current; 
    current = list->head; 

    while(current != NULL) 
    { 
    printf("Weight = %d\n", current->data->weight); 
    current = current->next; 
    } 
    } 
+1

只看你的代碼很快 - 當你插入()到一個空列表時,你malloc'ing兩個節點結構?這不是明顯的原因。 – DarenW 2013-05-03 05:10:16

回答

2

這些線可以被移除:

Node* current = (Node*)malloc(sizeof(Node)); 
current=newNode; 

此行並不需要的內存分配:

Node* temp = (Node*)malloc(sizeof(Node)); 

我敢打賭,你實際上是打破這一行雖然:

fscanf(f, " WGT_%d", &tempCan[ii].weight); 

tempCan不是一個數組,我不是100 %確定&tempCan[ii]會做什麼,但我懷疑你正在訪問tempCan指針位置的內存,並且它只能工作4次,因爲這是一些東西的大小。

+0

你是對的,我不能相信我錯過了。將其更改爲&tempCan-> weight並且它可以工作。謝謝! – Dawson 2013-05-03 05:02:35

+2

@Dawson:你最好刪除建議的行。如果沒有,你會遇到內存泄漏。 – Matthias 2013-05-03 05:05:01

+0

如果我在這裏刪除malloc,我將如何聲明temp Node * temp =(Node *)malloc(sizeof(Node)); – Dawson 2013-05-03 05:07:16

1

在for循環中,

fscanf(f, " WGT_%d", &tempCan[ii].weight); 

,而不是做

fscanf(f, " WGT_%d", &tempCan->weight); 

tempCan已撥款僅爲1元。當你的循環計數器遞增時,你訪問無效的位置。