我正在尝试使用 C 中的链表实现堆栈式结构。最终它将从输入文件中读取不同长度的字符串,因此需要动态内存。我在 printList 中的 printf 处遇到段错误,我无法弄清楚原因。我之前也遇到了推送中的段错误,但我似乎已经修复了它们。如果不是很明显,我的意图是仅将元素添加到列表的“顶部”。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void* emalloc(size_t n);
typedef struct node {
struct node* next;
char* word;
} node;
node* head = NULL;
void* emalloc(size_t n) {
void* p;
p = malloc(n);
if(p == NULL) {
fprintf(stderr, "Failed to allocate memory.");
exit(1);
}
return p;
}
void push(char* w) {
if(head == NULL) {
head = (node*) emalloc(sizeof(node));
head->word = (char*) emalloc(strlen(w) * sizeof(char) + 1);
strncpy(head->word, w, strlen(w) + 1);
printf("Pushed a word to head.");
return;
}
node* newnode = (node*) emalloc(sizeof(node));
newnode->word = (char*) emalloc(strlen(w) * sizeof(char) + 1);
strncpy(newnode->word, w, strlen(w) + 1);
newnode->next = head;
head = newnode;
}
void printList() {
node* cur = head;
if(cur == NULL || cur->word == NULL) printf("Whoops!");
while(cur != NULL) {
printf(cur->word);
cur = cur->next;
}
}
/*
* The encode() function may remain unchanged for A#4.
*/
void main() {
char word[20] = "Hello world";
//push("Hello",head);
//push("World",head);
//push("!",head);
push(word);
printList();
}
最佳答案
为什么要在 push() 中复制到字符串末尾的 1 后?此外,如果字符串太长,strncpy 不会为您将其置为 NUL。
真正的崩溃是在创建“Head”时,当没有条目存在时的第一个 if 语句。它不会将其下一个指针设为 NULL,因此列表遍历将在最后一个条目上爆炸,因为它读取列表末尾的垃圾指针。
关于c - 为什么打印链表内容时会出现段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55466013/