gpt4 book ai didi

c - 结构字段中的 strcpy/strncpy 段错误

转载 作者:行者123 更新时间:2023-11-30 17:23:09 25 4
gpt4 key购买 nike

我正在尝试向具有 char* 字段(单词)的结构添加一个新节点

Definition of 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 由用户使用 scanf 给出。 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);

}

我已经阅读了有关此问题的其他一些主题,并且我更改了函数以使用 word[] 而不是 char* 但它仍然不起作用。如果您需要更多信息,请告诉我。另外,当我使用 strndup 时,它有时可以正常工作,不会出现任何错误。

最佳答案

正如您所说,您有一个char *word,那么应该为该指针分配内存

newnode->word = malloc(sizeof(char) * (WORDLEN+1)); /* Please access the structure elements accordingly */

在向指针写入内容之前,应先为其分配内存。

关于c - 结构字段中的 strcpy/strncpy 段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27669795/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com