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;
    }
  }
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);

tempCan1 つの要素のみに割り当てられています。ループ カウンターが増加すると、無効な場所にアクセスします。

于 2013-05-03T05:01:51.943 に答える