Walking through heap ( C garbage collection )

Hello.
This is my homework for Computer Systems class.
So, don't give me the answers but rather hint at possible solutions or
highlight my mistakes please.

I know that I have 10000 blocks of increasing sizes in my heap
and I'm trying to walk through the heap and free all unused blocks.
I find the header of the first block and compute the address of the
header of the next block using the meta-data from the first block.
It works fine but there is trouble at the end of a 10000th block.

here is the output
.
.
freed block: 9995
sbrk(0) after free: 0x73e1000
sbrk(0) before free: 0x73e1000
freed block: 9996
sbrk(0) after free: 0x73e1000
sbrk(0) before free: 0x73e1000
freed block: 9997
sbrk(0) after free: 0x73e1000
sbrk(0) before free: 0x73e1000
freed block: 9998
sbrk(0) after free: 0x73e1000
sbrk(0) before free: 0x73e1000
freed block: 9999
sbrk(0) after free: 0x73e1000
sbrk(0) before free: 0x73e1000
freed block: 10000
sbrk(0) after free: 0x73e1000
sbrk(0) before free: 0x73e1000
freed block: 10001 sbrk(0)
after free: 0x1346000
Segmentation fault (core dumped)

As you can see, there appears to be an extraneous block, number 10001,
which also happens to be the same size as block 10000.
My algorithm frees it without a glitch and that last free changes sbrk(0)
to way lower value than it used to be.
Meanwhile, my algorithm keeps going and uses the meta-data from this
mysterious block number 10001 to compute the address of a next header
and... segfaults.

How can I make sure that my algorithm stops after 10000 allocations ( besides
hard-coding it in )?

Thank you.
Last edited on
1 way. meta-data in block 10000 should contain meta-data that it is the LAST block.
2 way. stop if you find that next block is located after address returned by sbrk()
Topic archived. No new replies allowed.