1

I'm trying to perform some operations like insertion and deletion in doubly linked list but after inserting 1-2 elements, the malloc() function is not allocating any memory. Here I'm showing a part of my code. Hope it helps

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

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

Here is the code for the creation of the 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;
        }

}

and here is the code for insertion at the beginning of the list. After 1-2 insertions, no more insertion is possible due to no memory.

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;
        }
}

Also, I want to state that I have 4 GB RAM. So, I don't find any reason for this behaviour.

I_Love_Islam
  • 73
  • 1
  • 3
  • 10

2 Answers2

2

You aren't allocating enough memory for your objects. Instead of allocating sizeof(struct node*) you want sizeof(struct node). I'm guessing the under-allocation is causing you to overwrite the memory.

DrC
  • 7,528
  • 1
  • 22
  • 37
2

sizeof(struct node *) is the size of a pointer, which is less than what you need for your struct, so you have undefined behavior. Instead, use:

malloc(sizeof(struct node))
Samuel Peter
  • 4,136
  • 2
  • 34
  • 42