Miguel Péres
Miguel Péres

Reputation: 640

Linked list node initialization, without using malloc()

I have this struct:

typedef struct chunk
{
  int size;
  int available;
  struct chunk* next;
} chunk;

I initialize one node doing this:

chunk* head, ptr;

chunk* node = (chunk*) brkOrigin;
node->size = alloc - sizeof(chunk);
node->available = 1;
node->next = NULL;

I'm not using malloc(), because this is an assignment which I have to implement myMalloc(), so brkOrigin is an address I got using sbrk(), before that piece of code. This is why I'm using this direct address instead of malloc(). But I don't know if it is correct to do like this, if someone has some idea on how to initialize a node of a liked list without malloc(), it would be nice too.

But I have to search the linked list, and I got some errors when trying this:

head = node;
ptr = head;

while(ptr != NULL)
{
  if(ptr->size >= mem && ptr->available == 1)
  {
  ptr->available = 0;

      if(ptr->size > mem)
      {
        //Split in two nodes. Basically, create another with the remainder of memory.   
      }
  }       
      else
        ptr = ptr->next;
}

The errors:

error: incompatible types when assigning to type ‘chunk’ from type ‘struct chunk *’
   ptr = head;


error: invalid operands to binary != (have ‘chunk’ and ‘void *’)
   while(ptr != NULL)

error: invalid type argument of ‘->’ (have ‘chunk’)
     if(ptr->size >= mem && ptr->available == 1)

error: invalid type argument of ‘->’ (have ‘chunk’)
     if(ptr->size >= mem && ptr->available == 1)

error: invalid type argument of ‘->’ (have ‘chunk’)
       ptr->available = 0;

error: invalid type argument of ‘->’ (have ‘chunk’)
       if(ptr->size > mem)

error: invalid type argument of ‘->’ (have ‘chunk’)
       ptr = ptr->next;

Sorry if this is a dumb question (or a dumb mistake), this is my first time using (actively) Stack Overflow. I can't understand this errors. But I'm almost sure the problem is with the node initialization without malloc()...

Upvotes: 3

Views: 836

Answers (1)

Carl Norum
Carl Norum

Reputation: 224924

chunk* head, ptr isn't doing what you think it's doing. It's equivalent to:

chunk *head;
chunk ptr;

What you want is either:

chunk *head;
chunk *ptr;

or, on one line if you insist:

chunk *head, *ptr;

Here's a link to exactly your problem at the C FAQ. There are more commentaries and details available from there.

Upvotes: 8

Related Questions