c - 为什么打印链表内容时会出现段错误?

标签 c linked-list segmentation-fault stack malloc

我正在尝试使用 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/

相关文章:

c - 如何递归提取目录?

c - 反转列表迭代逻辑错误

java - 按顺序从单链列表中删除重复项

c - malloc() 中的段错误?

ruby - 为什么这个 RMagick 调用会产生段错误?

c - 在 C 中的 vector 函数序列中避免(初学者)分配错误

将 8 位 sse 寄存器转换为 16 位短路

java - 在Java中创建通用有序链表,使用compareTo()时遇到问题

c - 为什么我的悬挂指针不会导致段错误?

在两个结构体数组变量之间复制数据