08Pointers and the heap
Growing and shrinking
Change the size of a heap block while keeping what it holds.
A block from the heap can change size. Growing keeps all that is in it so far; shrinking keeps what still fits. This program builds a list that grows as numbers arrive. It starts with room for 4 and doubles the room each time the list is full:
စံကား
Expected output
၁
၄
၉
၁၆
၂၅
၃၆
၄၉
၆၄
၈၁
၁၀၀
The room grows from 4 to 8 to 16 while the ten squares arrive. The counters are
လက္ခဏာမဲ့ ကိန်းပြည့် because sizes are never negative and the heap statements take that
kind.
| Zaka | Reads as |
|---|---|
ကိန်းများ လိပ်စာရှိကို | "the block at the address in list" |
မင်မိုရီ ကိန်းပြည့် ဆံ့နိုင်ရေ ခုစာ ဖြစ်အောင် | "so that it becomes big enough for room integers" |
နေရာအချဲ့အချုံ့လုပ်မည်။ | "will enlarge or shrink the room" |
What resizing does
- It can move the block to a new address. The owner gets the new address, so keep using that pointer. A borrow made before the resize would point at the old spot, so the compiler refuses a resize while a borrow of the block is still in use (see Pointer mistakes). Lend the block again after the resize.
- Growing keeps each value and adds new room after the last one. Shrinking keeps the values that still fit.
- Resizing a null pointer (
ဗလာ) is the same as asking for a new block. - If the heap has no room for the new size, the program stops with "no heap room". It stops rather than set the pointer to null, because that would lose the block the pointer still holds.
Hands on
- Start the list with room for 1 instead of 4. Does it still work?
- After the loop, shrink the block to fit
အရေအတွက်integers and no more. - Change the program to keep just the even squares.
Next: Ownership and borrowing.