So I've decided to dabble a bit into C, and while it's trippy as heck I've finished an implementation of a linked list for practice. I've pretty sure there's some type of obscure bug or memory leak in here some where since I really don't have a solid understanding of this language yet, so yeah, please review my code and thanks in advance!
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int val;
struct node* next;
} node_t;
void print_list(node_t* head){
node_t* current = head;
while(current!= NULL){
printf("%d\n", current->val);
current = current->next;
}
}
//Adding an item to the beginning of the list (pushing to the list)
node_t* push(node_t* head, int val){
node_t* new_node = malloc(sizeof(*new_node));
new_node->val = val;
new_node->next = head;
return new_node;
}
//Adding an item to the end of the list, returns new node
node_t* add(node_t* head, int val){
node_t* current = head;
while(current != NULL && current->next != NULL){
current = current->next;
}
current->next = malloc(sizeof(*current->next));
current->next->val = val;
current->next->next = NULL;
return current->next;
}
//Removing the first item (popping from the list)
//returns the value of the pop and removes the head
int pop(node_t** head){
if(*head == NULL){
return -1; //idk how to make some kind of error
}
node_t* next_node = (*head)->next;
int retval = (*head)->val;
free(*head);
*head = next_node; //so *head is the node_t* head, but we can still assign after freeing?
return retval;
}
int remove_last(node_t* head){
int retval;
if(head == NULL){
return -1;//once again, how to make error wtf
}
if(head->next == NULL){
retval = head->val;
free(head);
return retval;
}
//so at least 2 nodes in linked list
node_t* second_last = head;
while(second_last->next->next != NULL){
second_last = second_last->next;
}
retval = second_last->next->val;
free(second_last->next);
second_last->next = NULL;
return retval;
}
int main(){
node_t* head = NULL;
head = malloc(sizeof(*head));
head->val = 1;
head->next = malloc(sizeof(*head->next));
head->next->val = 2;
head->next->next = NULL;
printf("Starting list with 1, 2\n");
print_list(head);
head = push(head, 5);
printf("List with 5 pushed to the front\n");
print_list(head);
add(head, 9);
printf("List with 9 added to end\n");
print_list(head);
pop(&head);
printf("List with first removed\n");
print_list(head);
remove_last(head);
printf("List with last removed\n");
print_list(head);
return 0;
}
sizeof ref_objectinmalloc(). \$\endgroup\$