I wrote function - malloc, free and realloc The malloc function work fine. The problem is in the function of the realloc it returns me Segmentation fault and I do not know why this is happening. I would be happy if you help me to Understand why this is happening שand how I can fix it.
My code -
#include <unistd.h>
#include <stdio.h>
void *malloc (size_t size);
void *realloc (void *ptr, size_t size);
void free (void *ptr);
typedef struct metadata_block *p_block;
struct metadata_block
{
size_t size;
p_block next;
int free;
};
p_block head = NULL;
int
main ()
{
char *str;
int *a;
a = (int *) malloc (4);
scanf ("%d", a);
printf ("String = %d\n", *a);
a = (int *) realloc (str, 25);
scanf ("%d", a);
printf ("String = %d\n", *a);
return 0;
}
void *
malloc (size_t size)
{
void *my_malloc;
p_block tmp;
if (size <= 0)
{
return NULL;
}
if (head == NULL)
{
head = (void *) sbrk (size + sizeof (struct metadata_block));
head->size = size;
head->free = 0;
head->next = NULL;
return (void *) head + sizeof (struct metadata_block);
}
else
{
p_block tmp = head;
while (tmp->next != NULL)
{
tmp = tmp->next;
}
tmp->next = (void *) sbrk (size + sizeof (struct metadata_block));
tmp->size = size;
tmp->free = 1;
tmp->next = NULL;
return (void *) size + sizeof (struct metadata_block);
}
}
void *
realloc (void *ptr, size_t size)
{
void *newptr;
if (ptr == NULL)
{
return malloc (size);
}
if (size == 0)
{
return (ptr);
}
newptr = malloc (size);
return (newptr);
}
void
free (void *ptr)
{
p_block tmp;
if (tmp->free == 1)
{
tmp = 0;
}
ptr = NULL;
}