gpt4 book ai didi

c - c中链表期间的段错误

转载 作者:太空宇宙 更新时间:2023-11-04 06:34:09 25 4
gpt4 key购买 nike

当我尝试打印出我的链接列表时遇到段错误。谁能解释为什么?我知道段错误意味着我正在访问我不应该访问的内存。我假设这意味着我没有正确设置我的指针。任何帮助都会很棒。我的代码...

#include <stdio.h>
#include <stdlib.h>


struct node
{
int val;
struct node *next;
}*head;

typedef struct node item;

int main() {

item *curr, *head;

head = NULL;

char word = 'y';
//int num[10];
//int i = 0;

while (word == 'y'){
printf("Would you like to enter an integer? (y/n) ");
scanf("%s", &word);

if(word == 'y'){
int temp = 0;
printf("Enter an integer: ");
scanf("%d", &temp);
curr = (item *)malloc(sizeof(item));
curr->val = temp;
if (head == NULL){
head = curr;
head->next = NULL;
}
else {
curr->next = head;
head = curr;
}
}
}

curr = head;

while(curr != NULL) {
printf("%d\n", curr->val); //seg fault happens here
curr = curr->next ;
}
return 0;
}

最佳答案

这个:

scanf("%s", &word);

是缓冲区溢出,因为 %s 将读取一个 string,但您只有一个字符。这会调用未定义的行为;即使您只输入一个字符,scanf() 也会在该字符后添加 0 终止符以生成正确的字符串。

改变word的声明:

char word[32];

并以明确的大小进行扫描,以防止 scanf() 写入缓冲区之外:

scanf("%30s", word);

还要检查所有 I/O 和内存分配调用的返回值,因为它们可能会失败。

最后,don't cast the return value of malloc(), in C .

关于c - c中链表期间的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16892224/

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