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;

}

链表.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);

链表.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;
    }
  }
4

2 回答 2

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,因为这是某些东西的大小。

于 2013-05-03T05:00:28.983 回答
1

在 for 循环中,

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

而是做

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

tempCan仅分配了 1 个元素。随着循环计数器的增加,您将访问无效位置。

于 2013-05-03T05:01:51.943 回答