So I decided to learn C language this week, and I thought that implementing a linked list in C blindly is a good way to learn it(probably not), but now I'm stuck on this problem.
In my C code, I have an append()
function that adds an element to the linked list and a remove_index()
function that removes element on a certain index of the linked list, all seems to work fine when adding and removing element when I display the current linked list elements, but when I started to look at the memory usage of my program... after I delete and free() some of the index/node of the liked list using my remove_index()
function, the memory of my program doesn't seems to go down... what am I doing wrong here?
below is my code
#include <stdio.h>
#include <stdlib.h>
typedef struct linkedlist * int_list;
#define new_int_list() (struct linkedlist*) malloc(sizeof(struct linkedlist))
struct node
{
int value;
struct node *next;
};
struct linkedlist
{
size_t length;
struct node *head;
struct node *tail;
};
void append(struct linkedlist *list, int value)
{
struct node *newnode = (struct node*) malloc(sizeof(struct node));
newnode->value = value;
newnode->next = NULL;
if(list->head==NULL)
{
list->head = newnode;
list->tail = newnode;
list->tail->next = NULL;
list->length = 1;
}
else{
list->tail->next = newnode;
list->tail = newnode;
list->tail->next = NULL;
list->length++;
}
}
void remove_index_raw(const char* srcs, size_t line, struct linkedlist *list, size_t index)
{
if(list->length==0) return;
else if(index<0 || index>=list->length)
{
printf("\n\nError in file '%s' on line %ld:\n\tindex provided value is (%ld)\n\tList size is(%ld)\n\tindex overflow\n\n", srcs,line,index,list->length);
exit(2);
}
else if(index==0 && list->length==1){
free(list->head);
list->head == NULL;
list->tail == NULL;
list->length = 0;
return;
}
else if(index==0){
struct node *delete_first = list->head;
list->head = list->head->next;
free(delete_first);
list->length--;
return;
}
struct node *iterator = list->head;
while(--index) iterator = iterator->next;
struct node *delete_node = iterator->next;
iterator->next = iterator->next->next;
free(delete_node);
list->length--;
}
#define remove_index(list,index) remove_index_raw(__FILE__,__LINE__,list,index)
void display_list(struct linkedlist *list)
{
size_t iterate = list->length;
if(list->length==0) return;
struct node* start = list->head;
while(iterate){
--iterate;
printf("%d ",start->value);
start = start->next;
}
printf("\n");
}
void init_list(struct linkedlist *list)
{
list->head = NULL;
list->tail = NULL;
list->length = 0;
}
void main()
{
int MAX = 10000000;
int_list largelist = new_int_list();
init_list(largelist);
for(size_t i=0; i<MAX; ++i) append(largelist,i);
char pause;
printf("allocated");
scanf("%c",&pause);
for(size_t i=0; i<MAX; ++i) remove_index(largelist,0);
printf("deallocated");
scanf("%c",&pause);
scanf("%c",&pause);
}