Link to home
Start Free TrialLog in
Avatar of lordiano
lordiano

asked on

Malloc and Free question

Hi this is what I have

struct simple_block{
 int block_number;
 struct simple_block *next;
 struct simple_block *last;
};

and I declare a
struct simple_block **block_tracker = (struct simple_block **)malloc(sizeof(struct simple_block *) * 12);

soo i have an array of 12 for block_list

and now whenever i add items into the array i would do

            (block_tracker[temp])->next = (struct simple_block *)malloc(sizeof(struct simple_block));
            (block_tracker[temp])->next->block_number = p->num;
            (block_tracker[temp])->next->next = NULL;
            (block_tracker[temp])->next->last = NULL;
            (block_tracker[temp])->last = (block_tracker[temp])->next;

my question is.. When I am finished using the block_tracker array, I wnat to free them, Can i just do a free(block_list)
or I have to go through every nodes and free every single one of them like free(block_tracker[1]) or if block_tracker[1]-> isi not NULL i have to free its linked brother as well..?
Thanks a lot!
ASKER CERTIFIED SOLUTION
Avatar of Mercantilum
Mercantilum
Flag of Japan image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial

By the way you should not need an array allocation as you do a chained-list.
I would do some thing like that:

1. give a name to this struct

typedef struct simple_block{
 int block_number;
 struct simple_block *next;
 struct simple_block *last;
} Block;


2. Global var

Block *block_trader = NULL;


3. Allocation function (items numbers start from zero)

// note: we could get an inverted list with block_trader is last number
// this would allow us not to find the last item :)

Block *alloc_block (void)
{
  static int number = 0;
  Block *p,*q;

  // new item
  q = (Block *)malloc (sizeof(Block));

  // cannot alloc
  if ( ! q) return (q);

  // default values
  q->block_number = number;
  q->next = q->last = NULL;

  // add item to the chain
  if ( ! block_trader) block_trader = q;
  else
  {
    // find last item
    for (p=block_trader ; p->next ; p=p->next) /* nothing */;
    p->next = q;
    q->last = p;
  }
 
  number++;
}


4. free routine

void free_all (void)
{
  Block *p,*q;

  for (p=block_trader ; p ; )
  {
    q=p->next;
    free(p);
    p=q;
  }
}
Avatar of lordiano
lordiano

ASKER

thanks a lot , i wanted the array structure cuz i need a O(1) time to access it.
The final picture of the block_tracker will be something like block_tracker[0] has some numbers of linked items, and might be different from all other block_tracker[i]
I need to access the block_tracker[number] from time to time to add more items to its linked list.
Thats why I am using array.

thanks alot for the malloc!