While loop in C exits in Repl.it but not when run locally with gcc

Viewed 133

I am fairly new to C but have been asked by my teacher to implement a linked list.

When I ran the code below in Repl.it it works, however when I running it on my machine with gcc on windows, it doesn't exit the while loop.

Any ideas?

#include <stdio.h>
#include <stdlib.h>

struct node *newNode(int);
void llAppend(int);
void llPrint(void);

struct node {
  int data;
  struct node *next;
};

struct node *ll;

int main(void) {

    llAppend(2);
    llAppend(3);

    llPrint();
}

struct node *newNode(int data) {
  struct node *tmp;

  tmp = malloc(sizeof (struct node));
  tmp->data = data;

  return tmp;
}

void llAppend(int data) {
  struct node *tmp;
  
  if (ll == NULL) {
    ll = newNode(data);
    return;
  }

  tmp = ll;
  while (tmp->next != NULL) {
    tmp = tmp->next;
  }
  tmp->next = newNode(data);
}

void llPrint(void) {
  struct node *tmp;

  tmp = ll;
  while (tmp != NULL) {
    printf("%d\n", tmp->data);
    tmp = tmp->next;
  }
}
2 Answers

It doesn't exit the while loop. Any ideas?

The issue is that you haven't initialized tmp->next in newNode(). Therefore, in the while loop, your code accesses uninitialized memory when it tries to check tmp->next.

When I ran the solution in Repl.it it worked completely fine.

It worked out of luck. There's no knowing what could happen when you access uninitialized memory. It's possible that tmp->next happened to be NULL so that the code worked in that case.

How to resolve?

You need to set tmp->next to NULL in newNode() like this:

tmp->next = NULL;

Also, always check the return value of malloc, to ensure that it is not NULL.

Corrected version:

struct node *newNode(int data) {
  struct node *tmp;

  tmp = malloc(sizeof (struct node));
  if (tmp == NULL) {
      exit(EXIT_FAILURE);
  }
  tmp->data = data;
  tmp->next = NULL;

  return tmp;
}

Also, consider using valgrind and gdb, which are powerful tools that can help you debug things like this.

Side note: your main function is missing a return statement -- add return EXIT_SUCCESS;

In newNode() you don't initialise the next member. It could have any value, not necessarily NULL.

Related