5.1.20C Programming

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

2,047 words9 min readdifficulty · medium

WHAT is a C string?

char s[6] = "Hello";   //  H  e  l  l  o  \0   <- 6 bytes used
Figure — String handling — char arrays, null terminator, strcpy, strcat, strlen, sprintf (dangers)

strlen — derive it from scratch


strcpy — copy including the terminator


strcat — append, but find the end first


sprintf — formatted writing, and why it's dangerous


Forecast-then-Verify


Flashcards

What marks the end of a C string?
The null terminator byte '\0' (value 0).
How many bytes does the string "Hi" occupy?
3 — two chars plus the '\0'.
What does strlen return for "Hello"?
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.

Connections

  • Pointers in C — a string is just a char * / decayed array.
  • Arrays vs Pointers — why sizeof differs for arrays and parameters.
  • Buffer Overflow & Memory Safety — the security consequence.
  • Undefined Behaviour in C — why C lets you write out of bounds.
  • printf format specifierssprintf/snprintf share %d %s %f.
  • Time Complexity — strlen/strcat are O(n)O(n); repeated strcat is O(n2)O(n^2).

Concept Map

ends with

forces convention

requires

used by

used by

used by

reserves 1 byte

copies the

forgetting size causes

writes past end causes

no bounds check causes

violated leads to

source of

C string is char array

Null terminator backslash-0

char pointer carries no length

Scan byte by byte

strlen counts chars

strcpy copies bytes

strcat appends

sprintf formats into buffer

Array needs length plus 1 bytes

Buffer overflow

Bugs and security holes

Hinglish (regional understanding)

Intuition Hinglish mein samjho

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.

Go deeper — visual, from zero

Test yourself — C Programming

Connections