YEH KYUN HOTA HAI (root cause):malloc ko ek single contiguous range of addresses return karni hoti hai. Heap ko free "holes" ki list ke roop mein manage kiya jaata hai. Jab tum mixed order mein alag-alag sizes ke malloc/free blocks karte ho, toh free holes live blocks ke saath interleave ho jaate hain. Tum do free holes ko tab tak merge nahi kar sakte jab tak woh memory mein physically adjacent na hon.
Heap ko ek linear array of bytes maano. Allocation ko (start, size) holes ki free-list se model karo. Ek bade hole [0, 100) se shuru karo.
Hum simulate karte hain malloc(n) = kisi hole se n bytes lo (first-fit), free(p) = ek hole return karo, adjacent neighbours ke saath coalescing karte hue agar adjacent hon.
Agar hum stack order mein free karte (free C, phir B, phir A), toh har free growing right-hand hole ke saath coalesce ho jaata aur heap ek bade [0,100) hole mein return ho jaata — zero fragmentation.
Real allocators har request ko ek block size tak round up karte hain (alignment + bookkeeping ke liye). Maano blocks 16 bytes ke multiples mein aate hain, plus ek 8-byte header.
Enough total free memory exist karti hai, lekin woh non-contiguous holes mein split hai, isliye koi single hole request ke liye itna bada nahi hota.
Internal fragmentation kya hai?
Allocator requested se bada block deta hai (rounding/alignment/header ki wajah se); block ke andar ka unused tail waste hota hai.
malloc do free holes ko badi request satisfy karne ke liye kyun combine nahi kar sakta?
malloc ko ek contiguous address range return karni hoti hai; non-adjacent holes ko live block ke across merge nahi kiya ja sakta.
Coalescing kya hai?
Ek naye freed block ko uske physically adjacent free neighbour ke saath merge karke ek bada hole banana.
Coalescing sirf un blocks ke beech kaam karti hai jo...?
Memory mein physically adjacent hain.
Request r, header h, alignment a diye hue allocated block size ka formula?
B = ceil((r+h)/a) * a
r=20, h=8, a=16 ke liye, internal waste hai?
32 - 20 = 12 bytes.
Nested allocations ke liye fragmentation avoid karne wala free order kaun sa hai?
LIFO / stack order (sabse recently allocated pehle free karo), taaki har free adjacent hole ke saath coalesce ho.
Kya fragmentation matlab memory leak hai?
Nahi — leaked memory kabhi free nahi hoti; fragmented memory IS free hoti hai lekin unusably arranged hoti hai.
Recall Feynman: ek 12-saal ke bacche ko explain karo
Tumhare toy box mein 100 blocks ki jagah hai. Tum toys nikalte aur rakhte rehte ho. Khelne ke baad tumhare paas yahan-wahan empty gaps ho jaate hain — kul khali jagah itni kaafi hai ki ek bada robot toy aa sake total mein — lekin gaps chhote hain aur doosre toys ke beech bikhar gaye hain. Robot ko ek badi khali jagah chahiye, aur woh nahi hai, chahe box "kaafi khali" ho. Yahi atka-hua feeling fragmentation hai. Agar tum hamesha last nikala hua toy pehle wapas rakho, toh khali jagah ek neat corner mein rehti hai aur robot fit ho jaata hai!