I have written a code to add a new member to a list . Its working fine when I take add two members. However, as soon as I add third and compile and run the code gives me an error. The code and error are as follow:
#include<stdio.h>
#include<stdlib.h>
struct list_no {
struct list_no *prev,*nest;
struct linked_list *fnl;
int seq_no;
};
static int counter = 0;
struct list_no *lists,*first;
int add_list()
{
struct list_no *temp;
counter++;
if(lists == '\0')
{
lists = (struct list_no *)malloc(sizeof(struct list_no));
lists->prev = '\0';
lists->nest = '\0';
lists->fnl = '\0';
lists->seq_no = 1;
first = lists;
}
else
{
temp = lists;
lists->nest = (struct list_no *)malloc(sizeof(struct linked_list));
lists = lists->nest;
lists->fnl = '\0';
lists->prev = temp;
lists->nest = NULL;
lists->seq_no = counter;
}
return 0;
}
int main()
{
int i=0,lcount;
int i=0,lcount;
char ch = 'y';
first = '\0';
lists = first;
int w;
while(i != 3)
{
add_list();
printf("\n the val ::%d\n",lists->seq_no);
i++;
}
return 0;
}
the error message coming after ./a.out is :
the val ::1
the val ::2
a.out: malloc.c:3097: sYSMALLOc: Assertion `(old_top == (((mbinptr) (((char *) &((av)->bins[((1) - 1) * 2])) - __builtin_offsetof (struct malloc_chunk, fd)))) && old_size == 0) || ((unsigned long) (old_size) >= (unsigned long)((((__builtin_offsetof (struct malloc_chunk, fd_nextsize))+((2 * (sizeof(size_t))) - 1)) & ~((2 * (sizeof(size_t))) - 1))) && ((old_top)->size & 0x1) && ((unsigned long)old_end & pagemask) == 0)' failed.
Aborted
Why its not able to add third member?
You overwrite your pointer
So
temppoints to the same memory aslists. Then you allocate memory forlists->neste. And after that, you letlistspoint to that memory, which means, alsotemppoints to it.Try