简体   繁体   中英

Cons function not working

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;
}

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM