C Segmentation Fault (core dumped) 链表

标签 c memory segmentation-fault void-pointers coredump

我一直收到 Segmentation Fault (core dumped) 运行时错误,我不知道为什么。

我的代码:

struct Node
{
    void *next;
    void *val;
};
typedef struct Node* NodePtr;

struct List
{
    NodePtr head;
};
typedef struct List* ListPtr;

ListPtr create()
{
    ListPtr ptr = malloc(sizeof(struct List));

    return ptr;
}

int insert(ListPtr list, void *obj)
{
    NodePtr newObj = malloc(sizeof(struct Node));

    //Cast next as a self referencing Node
    newObj->next = (NodePtr) newObj->next;

    //Point to beginning of list
    NodePtr current = list->head;

    if(list->head == NULL)
    {
        newObj->val = obj;
        list->head->next = newObj;
        newObj->next = NULL;

        return 1;
    }

    return 0;
}

int main(int argc, char *argv[])
{
    int x = 2;
    int *p = &x;

    ListPtr thing = create();

    insert(thing, p);

    return 0;
}

错误在这里:list->head->next = newObj 经过一些调试。我以为我必须为 list->head->next 分配内存,但是当我为此添加代码时,它仍然给了我同样的错误。我是投错了还是没有正确分配内存?任何帮助将不胜感激,谢谢!

最佳答案

把它放在一起,运行良好。

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


struct Node {
        void *next;
        void *val;
};
typedef struct Node* NodePtr;

struct List {
    NodePtr head;
};
typedef struct List* ListPtr;

ListPtr CreateList() {
    ListPtr ptr = malloc(sizeof(struct List));
    return ptr;
}

void Insert(ListPtr list, void *obj) {
        // create and initialize new node
    NodePtr newObj = malloc(sizeof(struct Node));
    newObj->val = obj;
    newObj->next = NULL;

    //Point to beginning of list
    NodePtr curr = list->head;
    // Add node to the list
    if(curr == NULL) // if no head node, make newObj the head node
    {
        list->head = newObj;
    }
    else{ // otherwise traverse the list until you find the last node (the one that points to a null as the next)
        while(1) {
                if(curr->next != NULL) {
                        curr = curr -> next;
                } else {
                        curr->next = newObj;
                }
                list->head = newObj;
                newObj->val = obj;
                list->head->next = newObj;
                newObj->next = NULL;
        }
    }
}
int main() {
    int x = 2;
    int *p = &x;

    ListPtr thing = CreateList();

    Insert(thing, p);

    return 0;
}

关于C Segmentation Fault (core dumped) 链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32875500/

相关文章:

c - 我应该在使用数据上的 DB_DBT_MALLOcflags调用 DB->put 后​​释放数据吗?

c - 如果在堆栈上分配结构,则会发出警告

java - 在 Java 中以节省内存的方式读取一个巨大的数字文件?

c# - 内存扫描仪未找到结果

c++ - Linux 中的段错误,在 Mac OS 上工作正常

创建列表的列表(结构)

c - libmysql mysql_real_connect 在 localhost 上失败,但在本地 IP 地址上工作

python - 在 Python 中即时在磁盘上构造稀疏矩阵

c - 为什么这个程序会抛出段错误异常?

c - 在递归中传递指针会导致段错误