C 例:メモリリーク検査:ブロック数とバイト数の追跡
malloc/free をラップし、ブロック前にサイズを記録する Header を置き、生存ブロック数とバイト数を追跡します。alloc/free のたびに残量を表示。3回確保・2回解放・1回を意図的にリークし、最後に live blocks と bytes を報告する最小のリーク検出器です。
🖥 オンライン実行GCC 10.2 · C11 標準 · ▶ を押して実行 · コードをコピー
🖨 参考出力標準 C11 環境でのオンライン実行結果と一致
alloc 20 bytes -> live=1 bytes=20 alloc 32 bytes -> live=2 bytes=52 alloc 32 bytes -> live=3 bytes=84 a[4]=16 b="tracked buffer" c[3]=4.5 free 32 bytes -> live=2 bytes=52 free 20 bytes -> live=1 bytes=32 --- intentional leak of c --- final live blocks=1 bytes=32
🧩 学習を続ける