c语言 - 在链表中,最后一个节点>下一个不是 NULL,从而导致段错误



此函数将新元素添加到链表中,发生段错误是因为它尝试访问不应该存在的节点的字段(名称(。但是,添加的第一个节点具有 ->next = NULL,所以我不确定为什么它会进入 while 循环

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node {
char name[50];
struct node *next;
} *list;
list head = NULL;   //global variable
void add (char *name) {   //push
//check if it already exists
list node = head;
printf("naddent "%s"head->name (prev inserted): %sn",name,head->name);
printf("****while:n");
while(node != NULL){
printf("node: %pn",node);      
printf("node->name: %sn",node->name);
if(strcmp(node->name,name) == 0)
return;
node = node->next;
}
list newNode = malloc(sizeof(list)); 
strcpy(newNode->name, name);
newNode->next = head;
head = newNode;
}
int main(){
char name[50];
while(/*condition*/) {
scanf("%s", name);
add (name);
}
return 0;
}

输入:

nameOne
nameTwo
nameThree
nameFour

我添加了printf进行调试,我发现最后一个node->next不是NULL(因为它应该(,而只是"nameFour",因此在尝试访问node->name时会发生SEGFAULT。 提前谢谢。

此语句

printf("naddent "%s"head->name (prev inserted): %sn",name,head->name);

已经调用了未定义的行为,因为最初head可以等于NULL。因此,您不能像执行head->name那样使用 null 指针访问结构的数据成员。

我想这个名字entity在这个声明中使用

list newNode = malloc(sizeof(entity)); 

是声明的类型定义名称,例如

typedef struct node entity;

在更新了问题中的代码后,变量head的声明应遵循结构的声明

typedef struct node {
char name[50];
struct node *next;
} *list;
list head = NULL;   //global variable

也在此调用的格式字符串中

printf("naddent "%s"head->name (prev inserted): %sn",name,head->name);
^^

存在无效的转义符号。

这是一个产生预期结果的演示性程序。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node {
char name[50];
struct node *next;
} *list;
list head = NULL;
typedef struct node entity;
void add( const char *name ) {   //push
//check if it already exists
list node = head;
while(node != NULL){
if(strcmp(node->name,name) == 0)
return;
node = node->next;
}
list newNode = malloc(sizeof(entity));  //create entity
strcpy(newNode->name, name);
newNode->next = head;
head = newNode;
}

void output()
{
for ( list current = head; current != NULL; current = current->next )
{
printf( ""%s" -> ", current->name );
}
puts( "NULL" );
}
int main(void) 
{
const char *s[] = { "nameOne", "nameTwo", "nameThree", "nameFour" };
const size_t N = sizeof( s ) / sizeof( *s );

for ( size_t i = 0; i < N; i++ ) add( s[i] );

output();

return 0;
}

程序输出为

"nameFour" -> "nameThree" -> "nameTwo" -> "nameOne" -> NULL

最新更新