5.1.15 · D4 · HinglishC Programming

ExercisesMemory layout — text, data, BSS, heap, stack segments

2,982 words14 min read↑ Read in English

5.1.15 · D4 · Coding › C Programming › Memory layout — text, data, BSS, heap, stack segments


Level 1 — Recognition

Yahan tumhe bas ye batana hai ki koi cheez kis segment mein rehti hai. Abhi koi reasoning chains nahi, sirf definitions ke against pattern-match karo.

Recall Solution 1.1
  • (i) a = 100Data. Global, non-zero value se initialized, toh literal 100 ko disk par store karna padega.
  • (ii) b = 0BSS. Global zero se initialized — koi information store nahi karni, bas "4 bytes reserve karo, 0 se fill karo."
  • (iii) cBSS. Global uninitialized ko C standard ke hisaab se zero treat kiya jaata hai.
  • (iv) Pointer msg ek non-zero address se initialized hai, toh msg khud Data mein rehta hai. Characters "hello" ek string literal hain → ye Text (read-only) segment mein rehte hain (ya ek read-only data area mein jo read-only image ka part hai). Inhe write nahi kar sakte.
Recall Solution 1.2
  • (a) heap top(2) program break. malloc call karne se break upar move ho sakta hai (higher address ki taraf).
  • (b) stack top(1) rsp. Ek frame push karna rsp ko decrease karta hai (stack neeche grow karta hai).

Level 2 — Application

Ab tum rules combine karte ho: static, function scope, aur pointers-vs-pointees.

Recall Solution 2.1
  • (A) total = 12Data. Global, non-zero initialized.
  • (B) count = 0BSS. static ise static storage duration deta hai (ye calls ke beech survive karta hai), aur ye zero hai → BSS.
  • (C) limit = 60Data. static, non-zero initializer → 60 ko store karna padega.
  • (D) tmpStack. tick ke frame ke andar plain local (automatic) variable; entry par janam leta hai, return par chala jaata hai.
  • (E) buf (pointer) → Stack (ye ek local automatic variable hai). 256 bytes jise ye point karta haiHeap, malloc dwara return kiya gaya, aur ye function se zyada der tak rehte hain jab tak free nahi karo.
Recall Solution 2.2
  1. True. Dono ki static storage duration hoti hai — ye poore program run ke liye exist karte hain. Function ke andar static sirf naam chhupata hai; lifetime global jaisi hi hoti hai.
  2. False. Globals BSS mein rehte hain aur C standard ke hisaab se zero guaranteed hote hain, toh g == 0.
  3. True. Locals stack par rehte hain, jo zeroed nahi hoti; bytes mein jo pehle tha wahi rehta hai → undefined value.

Level 3 — Analysis

Ab tum addresses aur file sizes ke baare mein reason karte ho, sirf names nahi.

Recall Solution 3.1
  • (i) Stack address 0x7ffe... heap 0x561f... se bahut bada hai. Ye layout se match karta hai: heap low baithe hai, stack high baithe hai, dono ke beech ek bada khaali gap hai.
  • (ii) Doosra block ...62a0 pehle ...6260 se bada hai (difference 0x40 = 64 bytes). Address badha, toh heap upar grow kiya (higher addresses ki taraf), jaise expect kiya tha.
  • (iii) Naya local b ...9a9c par a ke ...9abc se chhota hai (difference 0x20 = 32 bytes neeche). Address ghata, toh stack neeche grow kiya jab hum deeper call mein gaye. ✔ layout formula se consistent.
Recall Solution 3.2
  • (i) A mein array initialized hai (ek element bhi), toh poore 1,000,000 × 4 bytes ≈ 4,000,000 bytes literal values disk par store hone chahiye → ye data mein jaate hain. B mein array sab zero hai → ye bss mein jaata hai, jo sirf ek size record store karta hai, toh data chhota rehta hai aur bss ~4 MB bhar jaata hai.
  • (ii) File disk par text + data carry karta hai (bss sirf ek number hai, disk par real bytes nahi). Toh A bada hai. Difference ≈ 4000032 - 32 = 4{,}000{,}000 bytes ≈ 4 MB bada.
  • (iii) Same. Load time par OS bss region ko RAM mein reserve aur zero-fill karta hai, toh dono programs chalte waqt ek 4 MB array memory mein rakhte hain. Fark sirf disk size ka hai.

Level 4 — Synthesis

Ab tum multiple segments aur lifetimes ko ek judgement mein combine karte ho.

Recall Solution 4.1
  • (i) make_greeting buf ka pointer return karta hai, jo ek local hai. return ke baad, wo stack frame chala jaata hai. Caller ke paas ek dangling pointer hai memory ki taraf jo reuse ho jaayegi agli call mein — undefined behaviour. Dekho Pointers and dangling pointers.
  • (ii) buf Stack par hai (function ke frame mein automatic array). return par stack pointer wapas move hota hai aur 16 bytes free consider hoti hain; koi bhi baad ka function call inhe overwrite kar deta hai.
  • (iii) Do fixes:
    /* Fix A: heap par rakho, caller free karta hai */
    char *make_greeting(void) {
        char *buf = malloc(16);   // heap: function se zyada der rehta hai
        if (buf) strcpy(buf, "hi");
        return buf;               // caller ko free() karna hoga
    }
    /* Fix B: caller buffer supply karta hai, ownership ka sawaal nahi */
    void make_greeting(char *out, size_t n) {
        strncpy(out, "hi", n);
    }
    Fix A mein block Heap par rehta hai aur return ke baad survive karta hai (dekho malloc, calloc, realloc and free). Fix B mein storage caller ka hai — unka stack ya heap ho sakta hai — aur callee sirf usme likhta hai.
Recall Solution 4.1
  • (i) Program 1 → heap exhaustion (malloc eventually NULL return karta hai). Program 2 → stack overflow (rsp apni limit se aage push ho jaata hai).
  • (ii) Program 1 Heap exhaust karta hai (break chadta rehta hai). Program 2 Stack exhaust karta hai (frames neeche push hote rehte hain). Related: Buffer overflow and stack smashing aur Stack frames and the calling convention.
  • (iii) Heap upar grow karta hai low side se, stack neeche grow karta hai high side se, aur dono same middle gap mein khaate hain. Agar heap itna upar chadh jaaye ya stack itna neeche sink ho jaaye, toh wo milte hain — lekin har ek pehle apni guard/limit se takraata hai, toh do alag named crashes milte hain chahe dono ek hi address space region ke liye compete kar rahe hon. Dekho Virtual memory and paging ki wo gap kaise mapped hota hai.

Level 5 — Mastery

Poora multi-part reasoning jo segments, disk, RAM, aur lifetime ko ek saath bind karta hai.

Recall Solution 5.1

(i) Segments:

  • P table = {7}Data (initialized, non-zero element).
  • Q scratchBSS (global, uninitialized/zero).
  • R name[] = "grid" → ye ek writable char array hai literal se initialized, toh array khud Data mein rehta hai (5 bytes: g r i d \0). (Jis literal se ye copy kiya gaya wo read-only hai, lekin array ek mutable Data object hai.)
  • S static double cache[100000]BSS (static storage, zero-initialized).
  • T n = 5Stack (automatic local).
  • U heapbuf pointer → Stack; 500000*4 block → Heap.

(ii) On-disk contribution:

  • P: initialized array of 500000 × 4 = 2{,}000{,}000 bytes → disk par Data mein ≈ 2 MB.
  • Q: sab zero → BSS → disk par ≈ 0 (sirf ek size record).
  • S: zero → BSS → disk par ≈ 0.

(iii) Runtime RAM (sab reserved aur, BSS ke liye, zero-filled):

  • P: 2{,}000{,}000 bytes = 2 MB.
  • Q: 2{,}000{,}000 bytes = 2 MB (BSS runtime par bhi real RAM leta hai).
  • S: 100000 × 8 = 800{,}000 bytes = 0.8 MB.
  • U-block: 500000 × 4 = 2{,}000{,}000 bytes = heap par 2 MB.
  • Toh chahe Q aur S disk par ~0 cost karte hain, saath mein runtime par 2.8 MB RAM cost karte hain.

(iv) = {7} hatane se table all-zero ho jaata hai, toh ye Data → BSS migrate karta hai. size ka data column uske 2{,}000{,}000 bytes se shrink hoga, aur bss utna hi badh jaayega. Net: disk par file2 MB shrink hoti hai; runtime RAM unchanged rehta hai.

Recall Solution 5.2

Har item ka disk footprint compute karo:

  • (1) initialized long array → Data, 262144 × 8 = 2{,}097{,}152 bytes ≈ disk par 2 MB. Sabse bada.
  • (4) int small = 42 → Data, 4 bytes.
  • (3) char *p → Data pointer = 8 bytes (4-byte-ish literal "text" read-only text mein baitha hai, alag/tiny count hota hai).
  • (2) all-zero long array → BSS, disk par ≈ 0 bytes (sirf size record). Sabse chhota.

Order (disk par sabse bada → sabse chhota): (1) > (3) > (4) > (2). ( (3) ka pointer 8 bytes hai vs (4) ke 4 bytes, toh pointer int se aage nikal jaata hai.)


Connections

  • malloc, calloc, realloc and free — upar har *p block ka heap-side.
  • Stack frames and the calling convention — kyun locals return par vanish ho jaate hain (Ex 4.1).
  • Static and global variables — storage duration — Data-vs-BSS rule jo L1–L2 drive karta hai.
  • Pointers and dangling pointers — Ex 4.1 mein returned-buf bug.
  • Virtual memory and paging — Ex 4.2 mein shared middle gap.
  • Buffer overflow and stack smashing — stack ka danger end.