C - 检查指针是否为 NULL 时出现段错误

标签 c segmentation-fault

所以每次我尝试检查指针变量是否为 NULL 时都会遇到此段错误。错误来自添加函数中的这些代码行:

if (it->head == NULL){
        printf("worksfine");
    }

这是我的全部代码:

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

typedef struct Node{
    int val;
    struct Node *prev;
    struct Node *next;
} node;

typedef struct IteratorInt{
    node *head;
    node *tail;
    node *last;
} IteratorInt;

IteratorInt IteratorIntNew(){
    IteratorInt *listint;
    listint = malloc(sizeof(IteratorInt));
    listint->head = NULL;
    listint->tail = NULL;
    listint->last = NULL;
    printf("address made %u\n", listint);
    return *listint;
}

int add(IteratorInt *it, int v){
    node *n;
    n->val = v;
    n->next = NULL;
    n->prev = NULL;
    printf("func works\n");
    printf("n %d\n", n->val);
    printf("address %u", it);
    it->head = n;
    printf("result %d", it->head->val);
    if (it->head == NULL){
        printf("worksfine");
    }
   /* if (it->head == 0){
       it->head = n;
    }
    if (it->tail == 0){
        it->tail = n;
    }
    if (it->last == 0){
        it->last = n;
    }*/

    return 1;
}

int main() {
    IteratorInt lit = IteratorIntNew();
    printf("works %u", &lit);
    add(&lit, 10);

    /*printf("Node value %d\n", lit.head.val);
    add(&lit, 15);
    printf("Node value %d", lit.tail.val);*/
    return 0;
}

你能告诉我它有什么问题吗?以及如何解决?非常感谢。

最佳答案

在您的add 函数中,变量n 是一个未初始化的指针。所以这不是检查it->head的问题。

关于C - 检查指针是否为 NULL 时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47745046/

相关文章:

c - 如果没有存储类的全局变量默认为 'extern',那么为什么我无法访问该变量?

C 段错误,任何人都可以帮助我确定原因吗?

c++ - 将(共享指针的) vector 的值分配给共享指针导致段错误c++

C 数组赋值在越界时有效

c - 如何让 C 程序回复一封信并吐出其他内容?

将 mpi 与 openMP 结合起来

c++ - 用于管理路径/URL 的库

c - 反转每一个交替的 k 个节点

c - 从文件读取后打印链表的段错误

c - c 中的字符串作为数组