IDRASAcademic OS
Unit 2: Dynamic Memory Allocation (malloc, free) & Memory Leaks 40 mins study timeINTERMEDIATE

Heap Allocations (malloc, calloc, realloc, free) & Memory Leak Auditing

Managing runtime variable-sized memory buffers on the heap, heap metadata chunks, and debugging memory leaks with Valgrind.

Verified: Faculty Peer Review Board

Learning Objectives

    Essential Prerequisites

      Layer 1: Intuition & Why It Matters

      The Core Mental Model

      “Stack memory ek fixed size ka bag hai: function start hua to bag me space mila, function khatam hua to bag gayab! Lekin agar hume pehle se pata hi na ho ki user kitna data enter karega (jaise 10 students aayenge ya 10,000 students), tab hume Heap Memory chahiye hoti hai! malloc (Memory Allocate) ka matlab: "Operating System, mujhe Heap par n bytes ki jagah de do!" OS aapko us jagah ka starting address laakar de deta hai. Lekin sabse zaroori rule: Jitni jagah aapne malloc se maangi hai, kaam khatam hone par 'free(ptr)' karke wapas karni padegi! Agar aap free karna bhool gaye -> Memory Leak! Agar aapne ek hi jagah ko do baar free kar diya -> Double Free Crash!”

      Why This Exists

      Agar kisi server program me har request par 1 KB memory leak hoti rahe, to 1 hafte baad poora server RAM khatam hone ki wajah se crash (Out of Memory) ho jayega.

      Beginner Foundation

      Stack memory ek fixed size ka bag hai: function start hua to bag me space mila, function khatam hua to bag gayab! Lekin agar hume pehle se pata hi na ho ki user kitna data enter karega (jaise 10 students aayenge ya 10,000 students), tab hume Heap Memory chahiye hoti hai! malloc (Memory Allocate) ka matlab: "Operating System, mujhe Heap par n bytes...

      Micro Concepts Decomposition

      MICRO CONCEPT 1Canonical Object

      malloc vs calloc Allocation Invariants

      malloc allocates contiguous uninitialized bytes containing arbitrary memory garbage; calloc allocates and zeroes out all allocated memory.

      Key Takeaway: Always check if malloc returns NULL before dereferencing to prevent null pointer dereference crashes under OOM conditions.
      MICRO CONCEPT 2Canonical Object

      Dangling Pointers & Double-Free Exploits

      Calling free() marks a chunk as available on the glibc heap free-list but does not reset the pointer variable. Accessing it is undefined behavior.

      Key Takeaway: Immediately assign ptr = NULL after free(ptr) to neutralize dangling pointers and prevent double-free crashes.
      Layer 3 & 4: Formal Specification & Mechanism

      Hardware State Machine Architecture

      glibc malloc manages heap memory via chunk metadata headers (size, prev_size, A/M/P flags) and bin lists (fastbins, smallbins, largebins, unsorted bins). Functions: 1. void* malloc(size_t size): Allocates uninitialized chunk >= size bytes. 2. void* calloc(size_t num, size_t size): Allocates and clears memory to zero. Checks for arithmetic overflow (num * size). 3. void* realloc(void *ptr, size_t new_size): Resizes allocation in-place or allocates new chunk, copies existing data, and frees old chunk. 4. void free(void *ptr): Deallocates chunk, inserting it into appropriate free bin. Passing NULL is a no-op. Memory leak occurs when dynamically allocated memory loses all references without being released via free().
      1. malloc() checks thread arena bins for available cached chunks. 2. If no chunk available, invokes brk() or mmap() system call to request pages from kernel. 3. Kernel maps anonymous virtual memory pages and updates VMA table. 4. malloc returns pointer offset + 8 or + 16 bytes past chunk header to user. 5. free() links chunk back into free-list without immediately returning virtual pages to OS.
      Layer 7: Interactive Laboratory

      Interactive Simulator

      COA • SIMULATIONC Pointers, Memory Addresses & Dereferencing Simulator
      Launch Fullscreen Lab
      COA • CPU ARCHITECTUREOperand Fetch & Memory Dereference

      Addressing Modes & Effective Address (EA) Visualizer

      1. Instruction Opcode
      LOAD R1, 8(R2)
      Mode: INDEXED Addressing Mode
      Base register plus index/offset value
      2. Address Resolution Unit
      DERIVATION FORMULA:
      EA = [R2] + Displacement/Offset = 0x1004 + 0x0008 = 0x100C
      Resolved EA: 0x100C
      Memory Bus Accesses: 1 cycle(s)
      3. Final Operand Fetched
      0x7777 (MEM[0x100C])
      Ideal for array and struct indexing (Array base address + index * element size).
      CPU Internal Register FileWord-size: 16-bit
      R10x0000General Purpose
      R20x1004General Purpose
      PC0x0200Program Counter
      XR0x0008Index Register
      RAM Physical Address SpaceWord Addressable
      5200x9999Memory Word
      40960x0042Memory Word
      41000x2000Memory Word
      41080x7777Memory Word
      81920x5555Memory Word
      Layer 5: Step-by-Step Worked Numerical Example

      End-to-End Execution Trace

      Dynamic String Duplication: char *my_strdup(const char *src) { size_t len = strlen(src) + 1; char *dest = (char*)malloc(len); if (dest) memcpy(dest, src, len); return dest; } // Caller is responsible for calling free(dest).
      Layer 6: Active Runtime CodeLab

      Step-by-Step Code Execution (C)

      SQL Studio
      Font
      main.cGlacier Light
      Ln 1 • GCC 13
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      390 chars • 18 lines • Ln 1UTF-8 • 4 Spaces
      Interactive Terminal Shell

      Sandbox Terminal Ready

      Click Run Code or press Ctrl+Enter to compile and execute.

      ⚡ AURXON Bitstream Runtime v4.8IDRAS Academic Virtual Node
      Layer 8: Practice & Knowledge Verification

      Active Assessment Quiz

      No Practice Questions Configured

      Questions for this topic are currently undergoing faculty review.

      Academic Evaluation Preparation

      Viva Examination & University Scoring Strategy

      Standard Viva Examination Questions

      How to Write High-Scoring University Exam Answers

      Explain malloc, calloc, realloc, and free with prototypes and return types, draw the chunk structure showing header and payload, define memory leaks with code examples, and explain how to prevent dangling pointers.