c - 段错误: 11 when trying to print linked list

标签 c pointers null segmentation-fault

我对 C 相当陌生,我知道我可能在指针方面做错了什么,但我似乎无法准确指出我做错了什么。

这是链表的结构和函数:

// node structure
struct Node {
    int val;
    struct Node* next;
};

// singly linked list structure
struct LinkedList {
    int size;
    struct Node* head;
} LinkedList = {0, NULL};


// insert at head function
void InsertHead(struct LinkedList* list, int val) {
    struct Node* node = malloc(sizeof(struct Node));
    node->val = val;
    node->next = list->head;
    list->head = node;
    list->size++;
}

// print values in list
void PrintList(struct LinkedList* list) {
    struct Node* node = list->head;

    while (node != NULL) {
        printf("%d, ", node->val);
        node = node->next;
    }
    printf("\n");
}

当我尝试使用以下代码调用PrintList时:

// main function
int main() {
    struct LinkedList* mylist = malloc(sizeof(LinkedList));
    InsertHead(mylist, 4);
    InsertHead(mylist, 3);
    InsertHead(mylist, 1);

    // printf("%d, ", mylist->head->val);
    // printf("%d, ", mylist->head->next->val);
    // printf("%d, ", mylist->head->next->next->val);
    // printf("\n");
    PrintList(mylist);

    return 0;
}

我收到错误段错误:11

当我运行删除对 PrintList 函数的调用并取消注释 printf 语句时,我得到了所需的输出:

1,3,4,

我在这里缺少什么?

最佳答案

您永远不会初始化在 main() 顶部分配的 struct LinkedList

因此,当您遍历列表以打印它时,在显式插入的三个元素之后,最后一个元素的 next 字段将包含 head 中的任何垃圾。分配时原始 LinkedList 的 code> 字段。

要解决此问题,您可以使用 calloc 来分配它(这会在分配给您之前将分配的内存显式清零),或者编写一个同时分配 显式初始化一个 struct LinkedList

关于c - 段错误: 11 when trying to print linked list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57342641/

相关文章:

c - c中的 "PRIVATE"中的 "PRIVATE int func_name()"是什么意思?

c - 如果在使用 malloc 后它返回一个 NULL 指针并且您继续尝试使用该指针,会发生什么情况?

c - 有没有办法将所有指向已释放内存的指针设置为 NULL?

swift - UIImage 在 segue 推送时返回 nil

vba - MS Access : eval() returns NULL when accessing . 列(x,y)属性

c - 不正确的二进制文件读取

c - 为什么这个C scanf会自动跳过呢?

.net - 将 64 位偏移量添加到指针

c++ - 指向数组的指针和指向数组第一个元素的指针之间的区别

c++ - 将具有空值的字符数组写入文件流