5.1.20 · D3 · HinglishC Programming

Worked examplesString handling — char arrays, null terminator, strcpy, strcat, strlen, sprintf (dangers)

2,921 words13 min read↑ Read in English

5.1.20 · D3 · Coding › C Programming › String handling — char arrays, null terminator, strcpy, strc


Scenario matrix

Kisi bhi example se pehle, har distinct situation list karte hain jisme ek C string ho sakti hai. Agar koi bug ya surprise hai, woh in rows mein se kisi ek mein rehta hai.

Cell Case class Kya special hai Covered by
A Normal string, room to spare length + '\0' easily buffer mein fit ho jaata hai Ex 1
B Buffer exactly full len + 1 == size (the boundary) Ex 2
C Off-by-one overflow len + 1 > size exactly ek byte se Ex 3
D Empty / degenerate string length , pehla byte '\0' hai Ex 4
E Missing terminator array mein koi '\0' nahi → runaway scan Ex 5
F Concatenation overflow strlen(dst)+strlen(src)+1 > size Ex 6
G Limiting / cost behaviour repeated strcat → quadratic time Ex 7
H sprintf output buffer se lamba formatted text silently overflow karta hai Ex 8
I sizeof trap across a function boundary char * param vs real array Ex 9
J Bounded snprintf truncation (safe fix) output too long but koi overflow nahi Ex 10

Neeche har figure mein do colour conventions use hue hain:


Cell A — normal string with room

Figure — String handling — char arrays, null terminator, strcpy, strcat, strlen, sprintf (dangers)
  1. src ke bytes count karo. "dog" hai d o g '\0' = bytes. Yeh step kyun? Kyunki copy ko sabhi bytes move karni hain including terminator — figure mein coral box dekho.
  2. dst[8] mein copy karo. Hum bytes ek -byte array mein likhte hain. , toh koi overflow nahi. Yeh step kyun? Cell A "room to spare" se define hota hai — yeh safe baseline hai jiske against baad ke har bug ko measure karte hain.
  3. my_strlen(dst) scan karta hai d(1) o(2) g(3) '\0'(stop) aur return karta hai . Yeh step kyun? Length '\0' se pehle ke characters count karta hai, isliye count hai, nahi.
Recall Verify

Reveal ::: strlen("dog") == 3, copy ko bytes chahiye, ✓ koi overflow nahi.


Cell B — buffer exactly full (the boundary)

Figure — String handling — char arrays, null terminator, strcpy, strcat, strlen, sprintf (dangers)
  1. Terminator add karo. "cat" = c a t '\0' = bytes. Yeh step kyun? Har string literal silently '\0' append karta hai — aapko uske liye budget rakhna hoga.
  2. a[4] mein fit karo. bytes bytes mein: exactly full, len + 1 == size. Yeh step kyun? Yeh boundary case hai — legal hai, lekin zero slack hai. Ek aur character aur hum Cell C mein hain.
  3. strlen(a) scan karta hai c(1) a(2) t(3) '\0' → return karta hai .
Recall Verify

Reveal ::: strlen("cat") == 3 aur buffer size (exact fit) ✓.


Cell C — off-by-one overflow

Figure — String handling — char arrays, null terminator, strcpy, strcat, strlen, sprintf (dangers)
  1. Jo likhna hai usse count karo. "Hello" = H e l l o '\0' = bytes. Yeh step kyun? Paanch letters visible hain; chhata byte ('\0') invisible hai lekin mandatory hai.
  2. Buffer se compare karo. . strcpy byte index likhta hai array ke last valid index ke baad. Yeh step kyun? Cell C exactly len + 1 > size ek se hai — C mein sabse common real bug.
  3. C kya karta hai: kuch nahi rokta. Figure mein dashed coral box (neighbour ka byte) mein likh deta hai → buffer overflow, undefined behaviour. Yeh step kyun? Koi bounds check nahi (Buffer Overflow & Memory Safety); corruption ab crash kar sakta hai, baad mein, ya exploit ho sakta hai.
Recall Verify

Reveal ::: needed bytes , buffer , overflow amount byte ✓.


Cell D — empty / degenerate string

Figure — String handling — char arrays, null terminator, strcpy, strcat, strlen, sprintf (dangers)
  1. "" ka layout. Pehla byte already '\0' hai: \0 ? ? ?. Yeh step kyun? Empty string "no bytes" nahi hai — yeh ek byte hai, terminator, index par baitha hai.
  2. strlen(e) e[0] dekhta hai, turant '\0' milta hai, counter ke saath ruk jaata hai. Yeh step kyun? Yeh counting loop ki degenerate limit hai: ek bhi increment nahi chalta.
  3. strcpy(e, "") exactly ek byte copy karega ('\0') — hamesha safe, chahe -byte buffer mein bhi.
Recall Verify

Reveal ::: strlen("") == 0 ✓; phir bhi byte occupy karta hai (the terminator).


Cell E — missing terminator (runaway scan)

Figure — String handling — char arrays, null terminator, strcpy, strcat, strlen, sprintf (dangers)
  1. Trap pakdo. {'a','b','c'} teeno slots fill kar deta hai. Kahin koi '\0' nahi hai. Yeh step kyun? Curly-brace init terminator append nahi karta jab array exactly full ho — string literal se alag.
  2. strlen chalao. Woh a(1) b(2) c(3) count karta hai phir bad[3] read karta hai — array ke bahar — aur chalata rehta hai, jo bhi random bytes aage hain unhe count karta hai jab tak accidentally nahi milta. Yeh step kyun? Stop signal ke bina loop par terminate nahi ho sakta; woh neighbour ki memory mein walk kar jaata hai (dashed boxes).
  3. Result: undefined — print ho sakta hai, , ya crash. Koi correct answer nahi. Yeh step kyun? Cell E dikhata hai ki "letters sahi hain" kaafi nahi: terminator contract hai, letters nahi.
Recall Verify

Reveal ::: intended length , lekin declared bytes bina terminator ke ⇒ 3 + 1 = 4 > 3, toh koi '\0' fit nahi hoti ⇒ scan undefined hai ✓.


Cell F — concatenation overflow

Figure — String handling — char arrays, null terminator, strcpy, strcat, strlen, sprintf (dangers)
  1. Pieces measure karo. strlen("Hi") = 2, strlen("there") = 5. Yeh step kyun? strcat inhe jodta hai, toh final string "Hithere" hai length ki.
  2. Bytes needed compute karo. result length bytes. Yeh step kyun? Rule hai strlen(dst) + strlen(src) + 1 single joined terminator hai.
  3. Buffer se compare karo. ⇒ overflow by bytes (figure mein dashed boxes). Yeh step kyun? strcat pehle dst ke '\0' tak walk karta hai index par, phir t h e r e '\0' wahan se copy karta hai — indices , lekin valid indices tak rukti hain.
Recall Verify

Reveal ::: 2 + 5 + 1 = 8 needed, buffer , overflow bytes ✓; strlen("Hithere") == 7.


Cell G — limiting cost behaviour (quadratic strcat)

Figure — String handling — char arrays, null terminator, strcpy, strcat, strlen, sprintf (dangers)
  1. strcat ka hidden scan yaad karo. Append karne se pehle, woh dst ko start se '\0' tak walk karta hai. Har baar cost hai (Time Complexity). Yeh step kyun? Append khud sasta hai ( char), lekin end dhundhna nahi.
  2. Scans sum karo. Iteration par current length hai, toh scan karta hai lagbhag reads. Total: Yeh step kyun? add karne mein arithmetic-series formula use hota hai — yeh "Shlemiel the painter" curve hai.
  3. Interpret karo. single characters append karne ke liye humne byte-reads kiye — mein quadratic, linear nahi. Yeh step kyun? Yeh limiting behaviour cell hai: correctness theek hai, lekin cost badhne ke saath explode hoti hai.
Recall Verify

Reveal ::: ✓.


Cell H — sprintf output buffer se lamba

  1. Number format karo. %d 12345 ko characters '1' '2' '3' '4' '5' mein badalta hai. Yeh step kyun? sprintf text likhta hai, raw int nahi — paanch digits (printf format specifiers).
  2. Terminator add karo. sprintf hamesha '\0' append karta hai ⇒ bytes likhe. Yeh step kyun? Safe count mein bhi chahiye; yahan woh overflow aur bura karta hai.
  3. Buffer se compare karo. ⇒ overflow by bytes. sprintf ne kabhi dekha hi nahi buf ka size, toh woh rok nahi sakta. Yeh step kyun? Cell H sprintf-specific danger hai: size simply uske arguments mein se ek nahi hai.
Recall Verify

Reveal ::: ke digits , needed , buffer , overflow ✓.


Cell I — sizeof trap across a function

  1. Array pointer mein decay karta hai. Jab store pass hota hai, parameter buf ek char * hai, array nahi (Arrays vs Pointers). Yeh step kyun? Pointer sirf ek address hold karta hai — woh bhool jaata hai ki array bytes lamba hai.
  2. sizeof buf evaluate karo. -bit machine par, ek char * ka sizeof hai (pointer size), nahi. Yeh step kyun? Real array par sizeof uska byte count deta hai; pointer par woh pointer ka apna size deta hai.
  3. Consequence. snprintf ko bataya jaata hai ki buffer sirf bytes hai, toh woh output par truncate karta hai chahe available the — ek silent capacity bug (aur catastrophic hota agar intent plain sizeof-based strcpy ka hota). Yeh step kyun? Cell I dikhata hai ki danger overflow nahi balki function boundary par ek galat size number hai.
Recall Verify

Reveal ::: fill ke andar, sizeof buf == 8 (pointer), lekin real array sizeof store == 64 ✓ — dono alag hain.


Cell J — safe fix (snprintf truncation)

  1. Pura would-be length compute karo. "log_2024.txt" = characters. snprintf woh length return karta hai jo woh likhta (excluding '\0'), toh n == 12. Yeh step kyun? Yeh return value hai jisse truncation detect karte hain: agar n >= sizeof path, output cut hua.
  2. path mein actually kya aata hai. snprintf at most size - 1 = 7 characters plus ek guaranteed '\0' likhta hai: l o g _ 2 0 2 '\0'path == "log_202". Yeh step kyun? Cell J Cell H ka safe counterpart hai: overflow karne ki jagah, snprintf truncate karta hai aur hamesha terminate karta hai.
  3. Truncation check karo. Kyunki , caller jaanta hai ki naam truncate hua aur react kar sakta hai (aur allocate karo, error out karo). Yeh step kyun? Yahi toh n-functions ka poora point hai — ek seat-belt jo us crash ki report karta hai jise usne roka.
Recall Verify

Reveal ::: "log_2024.txt" ki full length (toh n == 12); stored chars , giving "log_202" ✓.


Connections

  • Parent topic — woh tools jinhe yeh examples exercise karte hain.
  • Buffer Overflow & Memory Safety — Cells C, F, H sab overflows hain.
  • Undefined Behaviour in C — isliye Cells C, E ka koi defined answer nahi.
  • Arrays vs Pointers — Cell I, sizeof trap.
  • Time Complexity — Cell G, quadratic strcat.
  • printf format specifiers — Cells H, J, %d/%s kaise expand karte hain.