char* フィールド (単語) を持つ構造体に新しいノードを追加しようとしています
listT の定義:
enum boolean {false, true};
struct list {
enum boolean sorted;
union{
int words;
char *word;
};
struct list* next;
struct list* previous;
};
typedef struct list listT;
add_word_node 関数は main によって次のように呼び出されadd_word_node(read_word, list_head)
てread_word
います。Word は文字列として渡されますが、strncpy の後には終端バイトがありません。
>Debugger:
add_word_node (word=0xbffff0fa "ally", head=0x804c038) at prog.c
>Debugger:
(gdb) p newnode->word
$2 = 0x804c068 "allyP\224\373\267\377\377\377\377"
listT *add_word_node(char word[], listT *head) {
listT *newnode;
listT *curr = NULL;//sorted
//listT *prev;//sorted
newnode = malloc(sizeof(listT)); /* allocate new node and check */
newnode->word = malloc(sizeof(char)* WORDLEN);
strncpy(newnode->word, word, strlen(word));
//newnode->word = strndup(word, strlen(word));
if (newnode == NULL) {
return (NULL);
}
if (head->sorted == false){ //eisagwgh sto telos ths listas
newnode->next = head;
head->previous->next = newnode;
newnode->previous = head->previous;
head->previous = newnode;
}else {
if(head->next == head){
newnode->next = head;
newnode->previous = head;
head->next = newnode;
head->previous = newnode;
}else{
for (curr = head->next; curr->next != NULL; curr = curr->next){//for( curr = head->next; ;){
if(curr == NULL) break;
if(strncmp(curr->word,newnode->word,strlen(word)) > 0) break;
//else curr= curr->next;
}
if(strncmp(curr->word,newnode->word,strlen(word))== 0){
return(curr);
}
newnode->next = curr;
newnode->previous = curr->previous;
newnode->previous->next = newnode;
newnode->next->previous = newnode;
}
}
return (newnode);
}
この問題に関する他のトピックをいくつか読み、char* の代わりに word[] を使用するように関数を変更しましたが、それでも機能しません。さらに情報が必要な場合は教えてください。また、strndup を使用すると、エラーなしで動作することがあります。