程序在运行后退出?

时间:2016-05-06 22:23:16

标签: c file memory-leaks

程序运行正常并显示我想要的数据但随后崩溃。我不认为这是链接列表中的内存泄漏,因为我已经尝试了很多方法来释放它,但没有一个工作。

#include "Buildings.h"

void displayBuilding(struct node *x){
    printf("Building Name: %s\n\tFloors: %d\n\tValue: %d\n\n", x->payload.name, x->payload.floors, x->payload.value);
    if(x->last!=1){
        displayBuilding(x->next);
    }
}

void insert(struct node *x, char str[50]){
    srand(t);
    int f = (rand() % 6)+1;
    int v = ((rand() % 20)+1)*f;
    //printf("Floors: %d and Value: %d\n", f, v);
    strcpy(x->payload.name, str);
    x->payload.floors = f;
    x->payload.value = v;
    srand(time(NULL));
    t+=f+v*(rand()%1000);
}

FILE* openData(FILE *f){
    f = fopen("Buildings-Data.txt", "r");
    if(f==NULL){
        printf("No File!");
        return 0;
    }
    return f;
}

void freeList(struct node* head)
{
   struct node* tmp;

   while (head != NULL)
    {
       tmp = head;
       head = head->next;
       free(tmp);
    }

}

int main(){
    FILE *f1;
    struct node *head;
    struct node *curr;
    head = malloc(sizeof(struct node));
    curr = malloc(sizeof(struct node));

    curr = head;
    int i;
    for(i=0;i<9;i++){
        curr->next = malloc(sizeof(struct node));
        curr = curr->next;
    }
    f1 = openData(f1);
    curr = head;
    int readNum;
    char trash;
    fscanf(f1, "%d", &readNum);
    fscanf(f1, "%c", &trash);
    for(i=0;i<readNum;i++){
        char str[50];
        fscanf(f1, "%s",str);
        insert(curr, str);
        curr->last = 0;
        if(readNum-i==1){
            curr->last = 1;
        }else{
            curr = curr->next;
        }
    }
    fscanf(f1, "%c", &trash);
    fclose(f1);
    curr = head;
    printf("\n");
    displayBuilding(curr);

    curr = head;
    freeList(head);

    return 0;
}

我的标题文件:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>

struct building{
    char name[50];
    int floors;
    int value;  
};
typedef struct building place;

struct node{
    place payload;
    struct node *next;
    int last;
};

int t = 500;

1 个答案:

答案 0 :(得分:1)

问题在于,当您创建链接列表时,您永远不会在列表的最后一个节点中将next设置为NULL。你需要在循环之后这样做:

for(i=0;i<9;i++){
    curr->next = malloc(sizeof(struct node));
    curr = curr->next;
}
curr->next = NULL;

因此,while (head != NULL)中的freeList()循环永不停止,并最终尝试释放列表最后一个节点中未初始化的指针。