5 — it counts chars BEFORE the '\0', not the terminator.
Why is strlen O(n)?
A char* stores no length, so it must scan byte-by-byte until '\0'.
What does strcpy copy that beginners forget?
It also copies the '\0', so dst needs len+1 bytes.
Why must dst for strcat hold strlen(dst)+strlen(src)+1?
To fit both strings plus one final '\0'.
What single byte does strcat overwrite in dst?
dst's old '\0', so the two strings join.
Why is sprintf dangerous?
It never knows buf's size and will overflow if output is too long.
What's the safe replacement for sprintf?
snprintf(buf, sizeof buf, ...) — bounded and always terminates.
Why can sizeof buf fail to give the buffer size?
If buf is a char* parameter, sizeof gives pointer size (8), not the array.
What happens in C if you write past an array's end?
Undefined behaviour — no bounds check; may crash or be exploited.
Recall Feynman: explain to a 12-year-old
Imagine a row of mailboxes, each holding one letter, spelling a word. There's no sign saying how
long the word is. So we put a special "STOP" mailbox (an empty one) right after the last
letter. To read the word you start at the front and keep going until you hit STOP. Copying a word
means copying every letter and the STOP box into a new row of boxes. The danger: if your new
row has only 5 boxes but the word + STOP needs 6, you scribble in a box that belongs to your
neighbour — and in C, no one stops you. That neighbour's mailbox bug is a buffer overflow.
Dekho, C mein "string" koi alag data type nahi hota — ye sirf ek char array hai jiske end mein
ek special byte hota hai: '\0' (null terminator, value zero). Yahi byte batata hai ki string
kahan khatam hui. strlen, strcpy, strcat, sprintf — saare functions array ko ek-ek byte
chalte hain jab tak ye '\0' na mil jaaye. Isliye "Hello" ki length 5 hai par memory mein 6 byte
lagta hai (5 letters + 1 terminator). Hamesha yaad rakho: size = characters + 1.
Ab asli khatra: C tumhe array ke bahar likhne se rokta nahi. Agar char buf[5] hai aur tum
strcpy(buf, "Hello") karte ho, to 6 byte 5 ki jagah mein ghus jaate hain — ye buffer overflow
hai, jo crash ya security bug bana deta hai. strcat aur bhi sneaky hai: usse pehle dst ka end
dhoondhna padta hai (extra scan), aur dst ko dono strings + ek '\0' ke liye bada hona chahiye.
Sabse dangerous hai sprintf — usse pata hi nahi hota ki buffer kitna bada hai. Ek %f 300+
characters bana sakta hai aur seedha overflow. Isliye hamesha snprintf(buf, sizeof buf, ...)
use karo — wo size jaanta hai, truncate karta hai overflow ki jagah, aur '\0' guarantee deta hai.
Ek aur trap: sizeof buf sahi answer sirf tab deta hai jab buf ek real array ho; agar wo function
ka char * parameter hai to sizeof pointer ka size (8) dega, buffer ka nahi. Short trick: "String
Needs Zero, Buffer Needs Room" — yahi 80% string bugs se bacha lega.