0
#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.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
moon
  • 1
  • 2
  • I don't want to use sbrk() and brk() I need just a simple malloc just for allocation not free and realloc and... – moon Jun 09 '15 at 12:51
  • Did you try using the debugger to find where it crashes? – lurker Jun 09 '15 at 12:53
  • DON't cast the return type of malloc! – Zelldon Jun 09 '15 at 12:57
  • 5
    Welcome to Stack Overflow! Standard warning: [Do not cast the result of malloc](http://stackoverflow.com/q/605845/1151654) – Eregrith Jun 09 '15 at 12:58
  • Yes.but in returned value from malloc i get crash – moon Jun 09 '15 at 12:58
  • 1
    That's a risky and inefficient way to append a node to a list. – chqrlie Jun 09 '15 at 13:05
  • 2
    To avoid confusion, always use a distinguishable name for user defined functions. Don't use the same name as the library function itself. – Sourav Ghosh Jun 09 '15 at 13:05
  • compiling using gcc with '-Wall -Wextra -pedantic' exposes several problems with the code: 1) conflict with built-in function malloc() 2) 'NULL' not defined 3) control reached end of non-void function without a return statement. – user3629249 Jun 10 '15 at 05:28

2 Answers2

7

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;

Eregrith
  • 4,263
  • 18
  • 39
-2

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.

moon
  • 1
  • 2
  • 1
    Yeah, but you have to check if `malloc` didn't return NULL, otherwise your program will crash, when it will return NULL. Moreover you shouldn't really name your function `malloc`, as `stdlib` is often used library and you will have symbol clash. – zoska Jun 09 '15 at 13:46
  • 1
    Please don't comment your question in an answer. – Jabberwocky Jun 09 '15 at 14:02