2013-05-03 49 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元。当你的循环计数器递增时,你访问无效的位置。

相关问题