0

I am currently trying to program a function that will cons a new element onto the top of the list, and push the rest of the list back... can anyone help me with this? My program does not work when I try to compile and run it. It goes on an infinite loop. Any help?

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

/* linked lists of strings */

typedef struct sll sll;
struct sll {
  char *s;
  sll *next;
};

/* By convention, the empty list is NULL. */

/* sll_cons : (char*, sll*) -> sll* */
/* build new list with given string at the head */
/* note: copy the given string to the list (deep copy) */
sll *sll_cons(char *s, sll *ss) {
  while (ss != NULL) {
      char* temp;
      temp = malloc(sizeof(char)*strlen(ss->s));
      temp = ss->s;
      ss->s = s;
      ss->next = malloc(sizeof(char)*strlen(ss->s));
      ss->next->s = temp;
      ss->next->next = NULL;
      ss = ss->next;
  }
  return ss;
}
Leeho Lim
  • 19
  • 5

1 Answers1

0

Three things I want to mention here.

Point 1. You did not check for the success of malloc(). You're dereferencing the returned pointer immediately. If malloc() fails, you'll be facing UB. [ss->next->s]

Point 2. inside while loop, after allocating memory to ss->next, you're putting that to ss and then checking against not NULL, which will never usually be TRUE for malloc() success.

Point 3. temp = ss->s; no, that's not the way you perform a deep copy. You have to use strcpy(). Otherwise, there's no point allocating memory to temp.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • so to avoid this, should I add an "if" clause within the "while" statement? – Leeho Lim Feb 18 '15 at 05:34
  • @LeehoLim I did not look at your code logic, but yes, you should always check the return value of `malloc()` for NOT NULL and then use the returned pointer furthermore. – Sourav Ghosh Feb 18 '15 at 05:37