c - 双向链表中的插入和删除

标签 c memory linked-list malloc doubly-linked-list

我试图在双向链表中执行一些操作,例如插入和删除,但在插入 1-2 个元素后,malloc() 函数没有分配任何内存。在这里,我展示了我的代码的一部分。希望对你有帮助

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

struct node{
    int info;
    struct node *prev,*next;
}*start=NULL;

这里是创建DLL的代码

struct node* createlist()
{
    int data;
    printf("\nEnter the data: ");
    scanf("%d",&data);

        struct node* temp=(struct node *)malloc(sizeof(struct node*));
        if(temp==NULL){
        printf("\nOUT of Memory\n");
        return;
        }
        else{
        temp->info=data;
        temp->next=NULL;
        temp->prev=NULL;
        start=temp;
        }

}

这是在列表开头插入的代码。插入 1-2 次后,由于没有内存,无法再插入。

void insertatbeg(){
    int data;
    printf("\nEnter the data: ");
    scanf("%d",&data);
    struct node* temp=(struct node *)malloc(sizeof(struct node*));
        if(temp==NULL){
        printf("\nOUT of Memory\n");
        return;
        }
        else{
            temp->info=data;
            temp->prev=NULL;
            temp->next=start;
            start->prev=temp;
            start=temp;
        }
}

此外,我想声明我有 4 GB RAM。所以,我没有找到这种行为的任何原因。

最佳答案

您没有为您的对象分配足够的内存。而不是分配 sizeof(struct node*) 你想要 sizeof(struct node)。我猜分配不足导致您覆盖内存。

关于c - 双向链表中的插入和删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50891638/

相关文章:

链表删除元素函数的C实现

c++ - 删除链表的最后一个节点

c - Linux 内核(或其他低级别的东西)是如何编写 C 的 "good"示例

android - 如何诊断 Xamarin Android 弱引用表溢出的原因?

c - 如何使用 openmp 在 c 中进行具有一些 for 循环的任务并行化?

c++ - 3D vector 的 SSE 对齐

java - 尝试使用递归创建 removeLastElement

c - 在c中按字母顺序对链表进行排序

c - sendmsg/recvmsg 中的部分读/写问题

C - While 循环错误