c - 链表 - 添加节点时程序崩溃

标签 c loops linked-list

我的代码编译正确,但在我的 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,因为那是某物的大小。

关于c - 链表 - 添加节点时程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16351813/

相关文章:

vector - IDRIS向量与链表

c++ - 寻找一种快速填充 std::list 的方法

通过汇编比较 2 个数字

javascript - 我正在遍历数组并修改数组的内容,但没有得到预期的结果。

Javascript 异步循环变量

python - 循环控制,哪个更高效

c - 使用信号量和 pthreads 的生产者消费者程序

c++ - 如何在 hiredis 中使用 SADD 命令?

c - 使用位移位提取单词的部分内容时避免出现警告消息

c# - 为什么 StringBuilder 比字符串操作快,但 List<T> 比 LinkedList<T> 快?