【发布时间】:2021-01-27 20:33:39
【问题描述】:
我的代码采用一串由空格分隔的整数并从中构建一个链表,但 -1 除外。为什么打印nextNode -> data 会导致段错误?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node Node;
struct node {
int data;
Node *next;
};
void build_linked_list(Node **head_ptr) {
char *string = malloc(1028);
char *p = string, *found = string;
Node *nextNode = NULL;
if (fgets(string, 1028, stdin) != NULL) {
while ((found = strsep(&p, " \n")) != NULL) {
if (strcmp(found, "-1") == 1) {
Node *node = malloc(sizeof(Node));
node->data = atoi(found);
node->next = nextNode;
nextNode = node;
}
}
}
*head_ptr = nextNode;
printf("%i\n", nextNode->data); //error here
free(string);
}
int main() {
Node *head = NULL;
build_linked_list(&head);
return EXIT_SUCCESS;
}
【问题讨论】:
-
你在阅读
nextNode->data之前没有检查nextNode != NULL。 -
仅供参考,如果两个字符串不匹配,strcmp 将返回非零(负值或正值),因此您不应测试值 1。
-
我能看到的嫌疑人是
strcmp(found, "-1") == 1。你真的关心字符串相对于“-1”的字典顺序吗?如果你只是想检查它不是“-1”,条件应该是strcmp(found, "-1") != 0
标签: c linked-list segmentation-fault