Simple malloc function in c

234 views Asked by At
#define SIZE 7000

static char buf[SIZE]; 
static char *bufptr = buf;

struct node 
{
    int reg_num;
    int val;
    char var_name[30];
    char var_str[100];
    struct node *memroy;
    struct node *next;
};

struct node* add(struct node *head, int i)
{
    struct node *temp;

    if (head == NULL)
    {
        temp = (struct node *)malloc(sizeof(struct node));
        temp->next = NULL;
        temp->reg_num = i;
        head = temp;
    }
    else
    {
        head->next = add(head->next, i);
    }
    return head;
} 


void* malloc(int n) 
{
    if (buf + SIZE - bufptr >= n) 
    { 
        bufptr += n;
        return bufptr - n;
    }
    else
    {
        return NULL;
    }
}

When I run my programm it crashes during the assignment temp->next = NULL.

I think the problem is in my malloc function. I tested it with malloc in libraries and it worked correctly, but I not allowed to use libraries and must write a new malloc function.

2

There are 2 answers

2
moon On

My problem don't has relation with kind of pointer and returned value from
malloc().I have problem with size of buf[] and by
increment of size my problem solved.Tnx from every one.

0
Eregrith On

You never check the return of your malloc yet you know it can return NULL;.
Check if temp is NULL before doing temp->next = NULL;