Skip to content
BIASED
Back to topic

Optional

malloc/free and block coalesce

On a free-list allocate, free and coalesce neighbors; check fragmentation.

Version
v2
Minutes
~25
Evidence
Self-check in the notebook

Until platform auto-check exists, compare cell output with the expected numbers in the notebook. This is not a debt and does not affect mastery.

Download .ipynb

Download the notebook and run it locally. Its environment requirements are listed inside.

Notebook contents

Readable on your phone. The code below has not been executed in the browser; download the notebook to run it.

CA · malloc/free и coalesce / malloc/free and block coalesce

Activity version: 2 · Seed: n/a · Данные: toy heap of 6464 bytes with an explicit free list; allocate three 1616-byte blocks, free, coalesce neighbors.

Ожидаемые числа
Step free blocks (start,size) largest free live bytes
init [(0,64)] 6464 00
after 3×malloc(16) [(48,16)] 1616 4848
free middle (16) [(16,16),(48,16)] 1616 3232
free first (0) + coalesce [(0,32),(48,16)] 3232 1616
free last (32) + coalesce [(0,64)] 6464 00
Самопроверка в ноутбуке

Активность не входит в процент освоения.

import numpy as np
 
 
class ToyHeap:
    def __init__(self, size=64):
        # blocks: list of dicts {start, size, free}
        self.blocks = [{"start": 0, "size": size, "free": True}]
        self.size = size
 
    def _coalesce(self):
        self.blocks.sort(key=lambda b: b["start"])
        out = []
        for b in self.blocks:
            if out and out[-1]["free"] and b["free"] and out[-1]["start"] + out[-1]["size"] == b["start"]:
                out[-1]["size"] += b["size"]
            else:
                out.append(dict(b))
        self.blocks = out
 
    def malloc(self, n):
        for b in self.blocks:
            if b["free"] and b["size"] >= n:
                start = b["start"]
                if b["size"] == n:
                    b["free"] = False
                else:
                    b["start"] += n
                    b["size"] -= n
                    self.blocks.append({"start": start, "size": n, "free": False})
                self.blocks.sort(key=lambda x: x["start"])
                return start
        return None
 
    def free(self, ptr):
        for b in self.blocks:
            if b["start"] == ptr and not b["free"]:
                b["free"] = True
                self._coalesce()
                return
        raise KeyError(ptr)
 
    def free_list(self):
        return [(b["start"], b["size"]) for b in self.blocks if b["free"]]
 
    def live_bytes(self):
        return sum(b["size"] for b in self.blocks if not b["free"])
 
    def largest_free(self):
        fl = self.free_list()
        return max((sz for _, sz in fl), default=0)
 
 
h = ToyHeap(64)
assert h.free_list() == [(0, 64)] and h.largest_free() == 64 and h.live_bytes() == 0
p0 = h.malloc(16)
p1 = h.malloc(16)
p2 = h.malloc(16)
assert (p0, p1, p2) == (0, 16, 32)
assert h.free_list() == [(48, 16)]
assert h.live_bytes() == 48 and h.largest_free() == 16
 
h.free(p1)
assert h.free_list() == [(16, 16), (48, 16)]
assert h.largest_free() == 16 and h.live_bytes() == 32
 
h.free(p0)  # coalesce with middle hole
assert h.free_list() == [(0, 32), (48, 16)]
assert h.largest_free() == 32 and h.live_bytes() == 16
 
h.free(p2)  # coalesce across previous live block → one free region
assert h.free_list() == [(0, 64)]
assert h.largest_free() == 64 and h.live_bytes() == 0
# external fragmentation demo mid-run already checked (two size-16 holes, no size-32 until coalesce)
print("free", h.free_list())
print("OK: malloc/free coalesce")
 
Самопроверка в ноутбуке
  • после трёх malloc(16) остаётся (48,16)
  • free середины+начала → (0,32),(48,16)
  • полный free → снова (0,64)