The program runs fine and displays the data I want but then crashes. I don't think it is a memory leak from the linked list because I've tried many ways to free it and none have worked.
#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;
}
My header file:
#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;