[英]Linked List - program crashes while adding nodes
我的代碼編譯正確,但在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;
}
}
這些行可以刪除:
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,因為這是一個大小的東西。
在for循環中,
fscanf(f, " WGT_%d", &tempCan[ii].weight);
相反
fscanf(f, " WGT_%d", &tempCan->weight);
tempCan
僅分配了1個元素。 隨着循環計數器遞增,您將訪問無效位置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.