Different results between online C compiler and compiling in cmd while trying to implement linkedlists

71 Views Asked by At

Actually the title is pretty self explanotary, I implement the linkedlist in online C compiler and the code correctly adds elements to the list, prints the list and then deletes the last element of the linkedlist. But when I compile the program in MinGW on cmd it enters a infinite loop, it doesn't even show the elements added just some random numbers looping and I haven't been able to pin-point the problem.

#include <stdlib.h>
typedef struct node{
    int data ;
    struct node *next ;
}node;
//
node* newNode(int value){
    node *n = malloc(sizeof(node));
    n->data = value;
    n->next = NULL;
}
//
typedef struct list{
    node *head;
    node *tail;
}list;
//
list* add(list *liste, int value){
    node *n = newNode(value);
    if(liste->tail == NULL){
        liste->tail = n;
    }
    n->next = liste->head;
    liste->head = n;
    return liste;
}
//
void gez(list *liste){
    node *ix = liste->head;
    while(ix != NULL){
        printf("%d\n",ix->data);
        ix = ix->next;
    }
}
//
list* cikar(list *liste){
    
    node *ix = liste->head;
    while (ix->next != liste->tail){
        ix = ix->next;
        }
    liste->tail = ix;
    ix->next = NULL;
    return liste;
}
//
int main(){
    list *l = malloc(sizeof(list));
    l = add(l,4);
    l = add(l,8);
    l = add(l,16);
    gez(l);
    l = cikar(l);
    printf("\n");
    gez(l);
    return 0;
}
1

There are 1 best solutions below

1
On

Your code has several bugs:

  1. head and tail have no initial value. This will cause indefinite behaviour in add. Change malloc to calloc will by default NULL initialize them or you have to manually do so.
  2. newNode has no return value. Return n.
  3. You didn't free memory when removing node. Before setting ix->next = NULL free(ix->next).