Worked examples — String handling — char arrays, null terminator, strcpy, strcat, strlen, sprintf (dangers)
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

srcke bytes count karo."dog"haid o g '\0'= bytes. Yeh step kyun? Kyunki copy ko sabhi bytes move karni hain including terminator — figure mein coral box dekho.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.my_strlen(dst)scan karta haid(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)

- 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. 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.strlen(a)scan karta haic(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

- 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. - Buffer se compare karo. .
strcpybyte index likhta hai array ke last valid index ke baad. Yeh step kyun? Cell C exactlylen + 1 > sizeek se hai — C mein sabse common real bug. - 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

""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.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.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)

- 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. strlenchalao. Woha(1) b(2) c(3)count karta hai phirbad[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).- 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

- Pieces measure karo.
strlen("Hi") = 2,strlen("there") = 5. Yeh step kyun?strcatinhe jodta hai, toh final string"Hithere"hai length ki. - Bytes needed compute karo. result length bytes.
Yeh step kyun? Rule hai
strlen(dst) + strlen(src) + 1— single joined terminator hai. - Buffer se compare karo. ⇒ overflow by bytes (figure mein dashed boxes).
Yeh step kyun?
strcatpehledstke'\0'tak walk karta hai index par, phirt 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)

strcatka hidden scan yaad karo. Append karne se pehle, wohdstko 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.- 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.
- 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
- Number format karo.
%d12345ko characters'1' '2' '3' '4' '5'mein badalta hai. Yeh step kyun?sprintftext likhta hai, raw int nahi — paanch digits (printf format specifiers). - Terminator add karo.
sprintfhamesha'\0'append karta hai ⇒ bytes likhe. Yeh step kyun? Safe count mein bhi chahiye; yahan woh overflow aur bura karta hai. - Buffer se compare karo. ⇒ overflow by bytes.
sprintfne kabhi dekha hi nahibufka size, toh woh rok nahi sakta. Yeh step kyun? Cell Hsprintf-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
- Array pointer mein decay karta hai. Jab
storepass hota hai, parameterbufekchar *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. sizeof bufevaluate karo. -bit machine par, ekchar *kasizeofhai (pointer size), nahi. Yeh step kyun? Real array parsizeofuska byte count deta hai; pointer par woh pointer ka apna size deta hai.- Consequence.
snprintfko 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 plainsizeof-basedstrcpyka 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)
- Pura would-be length compute karo.
"log_2024.txt"= characters.snprintfwoh length return karta hai jo woh likhta (excluding'\0'), tohn == 12. Yeh step kyun? Yeh return value hai jisse truncation detect karte hain: agarn >= sizeof path, output cut hua. pathmein actually kya aata hai.snprintfat mostsize - 1 = 7characters 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,snprintftruncate karta hai aur hamesha terminate karta hai.- 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,
sizeoftrap. - Time Complexity — Cell G, quadratic
strcat. - printf format specifiers — Cells H, J,
%d/%skaise expand karte hain.