Struggling to learn how malloc and free work, but I thought that I might of had it right. I am calling a deleteList() at the end of my test file which should free all the memory, but when I use valgrind it states I still have allocated memory active. If anyone knows how I might resolve this, it would be great.
Testing source file:
#include "stdlib.h"
#include "string.h"
#include "linked_list.h"
int main(int argc, char* argv[]){
PersonalInfo *head = NULL;
printList(head);
insertToList(&head, 2, "Mike", "Pealow");
printList(head);
deleteList(&head);
return 0;
}
Prototype file:
#define NAME_LENGTH 32
typedef struct personalInfo {
struct personalInfo *next;
unsigned int id;
char firstName[NAME_LENGTH];
char familyName[NAME_LENGTH];
} PersonalInfo;
PersonalInfo *insertToList(PersonalInfo **head, unsigned int id, char *firstName, char *familyName);
void printList(PersonalInfo *head);
void deleteList(PersonalInfo **head);
Source file:
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "linked_list.h"
PersonalInfo *insertToList(PersonalInfo **head, unsigned int id, char *firstName, char *familyName){
PersonalInfo *p = (PersonalInfo*)malloc(sizeof(PersonalInfo));
strcpy(p->firstName, firstName);
strcpy(p->familyName, familyName);
p->id = id;
p->next = NULL;
if(*head!=NULL && p!=NULL){
p->next = *head;
return p;
}
else{
printf("Head is null; create new head? (y/n)");
char scChar;
scanf("%c", &scChar);
if(scChar=='y'){
head = &p;
return p;
}
else if(scChar=='n'){
printf("Exiting");
free(p);
p=NULL;
return NULL;
}
else{
printf("Invalid input, exiting");
free(p);
p=NULL;
return NULL;
}
}
}
void printNode(PersonalInfo *node){
printf("%s %s %d", node->firstName, node->familyName, node->id);
}
void deleteList(PersonalInfo **head){
if(*head==NULL)
printf("List is empty\n");
PersonalInfo *next, *currNode = *head;
while(currNode!=NULL){
next = currNode->next;
free(currNode);
currNode = next;
}
currNode = NULL;
}