Hi everyone well currently I am working on a simple malloc and free implementation but I am facing some problems . I get a segmentation fault this is my output
inserting node 0 0xc87000
inserting node 1 0xc87014
inserting node 2 0xc87028
inserting node 3 0xc8703c
inserting node 4 0xc87050
inserting node 5 0xc87064
inserting node 6 0xc87078
inserting node 7 0xc8708c
inserting node 8 0xc870a0
inserting node 9 0xc870b4
The list head : 0xc87000 inside the del_search
returned value by the del_search 0xc87050
back 0x400c8703c
Segmentation fault (core dumped)
here is the code
typedef struct mem_chunk *ptr ;
int i=0;
ptr list_head =NULL ; // a pointer to the head of the list that will be used to link used chunks
typedef struct mem_chunk
{
size_t size;
ptr next;
ptr prev;
int flag;//if flag=1 then this chunk is free else if flag=0 then this chunk is used
void* mem_brk;
};
ptr del_search (void* node)
{
ptr temp;
temp=list_head;
printf("The list head : %p inside the del_search \n",temp);
while(temp != NULL )
{
if (temp->mem_brk==node)
{
printf("returned value by the del_search %p \n",temp);
return temp;
}
else
temp=temp->next;
}
return (ptr)-1;
}
int delete(void* node)// return 0 on success and -1 on failure
// currently not fully implemented still there are some cases not implemented
{
if (list_head==NULL) // when deleting from an empty list
return -1 ;
else
{
ptr temp;
temp=del_search(node);
if(temp ==(void*)-1) // the pointer was given by malloc
return -1;
else
{
ptr back , next;
next=temp->next;
temp->next->prev=temp->prev;
back=temp->prev;
printf("back %p\n",back);
void* brk=back->mem_brk;
back->next=next; // this what caused the segmentation fault
temp->flag=1;// making the node available
return 0;
}
return -1; // the pointer wasn't give by malloc
}
}
void free(void* brk)
{
if (brk==NULL)
return;
int temp;
temp=delete(brk);
if (temp==(ptr)-1)
return;
}
void main(){
ptr temp[10];
// printf("sbrk 0 %p \n",sbrk(0));
int i;
for(i=0 ;i<10 ;i++)
{
temp[i]=malloc(4); // malloc works properly also the insert function
}
free(temp[4]->mem_brk);
}
the problem is that the value of the pointer changes and I don't know why. so can anyone help ??