Question: C Program Freeing memory in linked list. Hi, this is my small program that reads in data and turns it into a linked list and

C Program Freeing memory in linked list.

Hi, this is my small program that reads in data and turns it into a linked list and prints it out. But my only issue is that I am having a massive memory leak. What can I do to fix it? Here is parts of my code to the program.

typedef struct Car {

char *model; char *color; int year; struct Car *next; } car;

int main(int argc, char *argv[]) {

if(argc!=2) { printf("Error wrong number of command line arguments"); }

char *input=argv[1];

FILE *file=fopen(input,"r");

if(file==NULL) { printf("Unable to open file "); exit(0); }

car *head=NULL;

head=readFile(file);

printCars(head);

free(head); fclose(file);

return 0; }

void printCars(car *head) {

car *p=head;

printf(" The list of cars in inventory are: ");

while(p!=NULL) { printf("%-5d %-20s %s ", p->year, p->model,p->color); p=p->next; } printf(" "); }

car* readFile(FILE *file){

char line[MAX_LINE],model[MAX_MODEL],color[MAX_MODEL],delimeter[2]="|"; char *token; car *head=NULL; int year;

while(fgets(line,MAX_LINE,file)!=NULL){

token=strtok(line,delimeter); strcpy(model,token);

token=strtok(NULL,delimeter); strcpy(color,token);

token=strtok(NULL,delimeter); year=atoi(token);

head=insertInSortedOrder(head,model,color,year); } return head; }

car *insertInSortedOrder(car *head, char *model, char *color, int year){

car *newcar=createCar(model,color,year); car *temp,*p;

if(head==NULL||strcmp(model,head->model)<0){ newcar->next=head; head=newcar;

return head; }

p=head;

while((p->next!=NULL)&&(strcmp(p->next->model,model)<0)){ p=p->next; }

temp=p->next; p->next=newcar; newcar->next=temp;

return head; }

car *createCar(char *model, char *color,int year){

car *temp;

temp=(car *)malloc(sizeof(car));

temp->model=strdup(model); temp->color=strdup(color); temp->year=year; temp->next=NULL;

return temp; }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!