A bug in my code

bearophile bearophileHUGS at lycos.com
Sat Sep 6 15:51:06 PDT 2008


Manfred_Nowak Wrote:
> >             this.list_tail.next = new_block;
> >             this.list_tail = new_block;
> > 
> What are you doing here?

Let's see. This is a singly linked list, the list header that is the pointer to the oldest allocated block is (this doesn't change often):
this.list_head
The last block of the linked list is pointed by:
this.list_tail
Each block has a "next" pointer.

When the user wants to add an item to the data structure and the last block is full, I have to allocate a new block, that is pointed by:
new_block

So I allocate:
new_block = GC_malloc ...

Then I set the 'next' pointer of the last block of the list (that was null) to point the new block:
this.list_tail.next = new_block;

Then I move the tail pointer to point to the newly allocate block:
this.list_tail = new_block;
So now the tail pointer correctly points to the last block.

Now I can reset to zero the number of the items in the last block:
this.used_last_block = 0;

Then I can copy the new item in the correct position, that is 0 if the block is newly allocated:
this.list_tail.data[this.used_last_block] = x;

Then I increment the number of items used in the last block, so next time I'll insert in the second space:
this.used_last_block++;

Then I increment the total length of the data structure, to remember how much long it is:
this.total_len++;

So that code looks correct to me.

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list