0

私は現在、リストの一番上に新しい要素をconsし、リストの残りを押し戻す関数をプログラムしようとしています...誰かがこれを手伝ってくれますか? プログラムをコンパイルして実行しようとすると、プログラムが機能しません。無限ループに陥ります。何か助けはありますか?

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

1 に答える 1

0

ここで言いたいことは3つ。

ポイント 1.の成功を確認していませんmalloc()。返されたポインターをすぐに逆参照しています。失敗した場合malloc()は、UB に直面することになります。[ ss->next->s]

ポイント 2. while ループ内で、メモリを に割り当てた後ss->next、それを に入れ、ssNULL でないことを確認します。これは通常、malloc()成功のために TRUE になることはありません。

ポイント 3.いいえ、それは ディープ コピーtemp = ss->s;を実行する方法ではありません。を使用する必要があります。そうでなければ、にメモリを割り当てても意味がありません。strcpy()temp

于 2015-02-18T05:32:34.940 に答える