Interview Q&A · C · 10 questions in this topic
Strings & <string.h> — C Interview Q&A
Null-terminated strings — the library functions, their safe variants, and the overflow discipline. Part of Arrays & Strings · 202 questions in the C bank.
How are C strings represented? What is the null terminator?
Answer
A C string is a char array ending with '\0' (value zero). Length (strlen) counts characters before it; storage needs length + 1 bytes. Every string function scans for the terminator — a missing one reads out of bounds.
The terminator is metadata and payload boundary in one byte, which is why C strings cannot contain embedded NULs.
Example
char s[] = "hi"; /* {'h','i','\0'}: 3 bytes for 2 chars */ /* strlen(s) == 2, sizeof s == 3 */
💡 Length + 1 for storage is the allocation rule every C programmer internalizes.
What is the difference between `strcpy`, `strncpy`, `snprintf` for copying?
Answer
strcpy copies to the terminator with no bounds — unsafe unless the destination provably fits. strncpy caps at n but may leave the result unterminated (no '\0' written when the source fills n). snprintf(dst, size, "%s", src) always terminates (C99) and reports truncation — the recommended copy.
Rule: know the destination size, always terminate, check truncation where it matters.
Example
char dst[8]; /* strcpy(dst, src); // unbounded: unsafe */ /* strncpy(dst, src, sizeof dst); // may not terminate! */ snprintf(dst, sizeof dst, "%s", src); /* terminates, detects cut */
How do `strcat`, `strncat`, `strcmp`, `strncmp` behave?
Answer
strcat appends from the terminator with no bounds — needs proven space. strncat appends at most n chars plus always writes '\0' (needs n+1 space accounting). strcmp/strncmp return <0/0/>0 by lexicographic (unsigned char) order; strncmp caps the comparison length.
Track remaining capacity explicitly (dst + used, size - used) instead of rescanning with strlen in loops.
Example
char buf[16] = "ab"; strncat(buf, "cdef", sizeof buf - strlen(buf) - 1); /* bounded */ /* strcmp(a, b) == 0 means equal */
💡 Remaining-capacity arithmetic (size - used - 1) is the strcat safety pattern.
What is the difference between `strlen`, `sizeof`, and `strnlen`?
Answer
strlen scans to '\0' at runtime (O(n), crashes on unterminated input). sizeof is compile-time storage bytes (includes the terminator for arrays, pointer size after decay). strnlen caps the scan at a maximum — safe against unterminated buffers.
Use strnlen with untrusted input, sizeof for stack-array capacity, strlen only where termination is guaranteed.
Example
char buf[64]; /* strnlen(buf, sizeof buf) // never reads past 64 */ /* strlen(buf) // UB if unterminated */
How do you parse strings to numbers safely (`atoi` vs `strtol`)?
Answer
atoi cannot report errors (returns 0 for both "0" and garbage) and has undefined overflow behavior. strtol reports via end-pointer plus errno: check ERANGE, verify end != start (digits consumed), skip trailing whitespace deliberately, and range-check before narrowing.
Wrap strtol once in a parse helper and ban atoi/strtol-raw from the codebase.
Example
#include <errno.h> #include <stdlib.h> long parse_long(const char *s, int *ok) { errno = 0; char *end = NULL; long v = strtol(s, &end, 10); *ok = (errno == 0 && end != s && *end == '\0'); return v; }
💡 end-pointer plus errno is the complete validation trio (range, consumption, termination).
What is string literal pooling and mutability?
Answer
Literals have static storage duration, typically in read-only memory, and identical literals may share one address (pooling). Writing through a non-const char* to a literal is undefined behavior — usually a segfault.
Always use const char* for literals; duplicate with strdup/malloc+strcpy when mutation is needed.
Example
const char *p = "shared"; /* read-only view */ char *m = strdup(p); /* owned mutable copy (free it) */ /* p[0] = 'S'; // UB: often segfault */
How do format-string vulnerabilities happen (`printf(user_input)`)?
Answer
Passing attacker-controlled text as the format string lets %x/%s/%n directives read stack memory and write to arbitrary addresses (%n writes the count so far). The fix is absolute: never let input be the format — printf("%s", input) — and compile with -Wformat-security.
%n (write-back) is the dangerous primitive; many hardened builds disable or gate it.
Example
/* VULNERABLE: printf(input); */ /* SAFE: printf("%s", input); */
How do you tokenize (`strtok` vs `strtok_r`) and why does it matter?
Answer
strtok splits on delimiters by writing '\0' into the input (destructive) and keeps static state — non-reentrant and thread-hostile. strtok_r takes an explicit save pointer, making it reentrant and thread-safe.
strtok also collapses consecutive delimiters and cannot parse empty fields — for CSV-style input, hand-roll with strchr/strspn or strsep (BSD).
Example
/* char *tok = strtok(buf, ","); // static state: unsafe */ /* char *save = NULL, *tok = strtok_r(buf, ",", &save); // safe */
How do you build strings safely (dynamic concatenation)?
Answer
Track length and capacity like a tiny vector: grow geometrically with realloc (temporary pattern), append with memcpy/snprintf into the tail, and always reserve the +1 terminator. Or use open_memstream/asprintf (GNU/POSIX) where available.
Quadratic strcat-in-a-loop (rescanning from the start each time) is both slow and overflow-prone — keep a tail pointer.
Example
/* keep (buf, len, cap); append: */ /* if (len + add + 1 > cap) grow(); */ /* memcpy(buf + len, src, add); len += add; buf[len] = '\0'; */
💡 Length-plus-capacity with geometric growth is the string-builder pattern in one sentence.
What is the difference between `char`, `signed char`, `unsigned char` and `uint8_t`?
Answer
char holds characters; its signedness is implementation-defined (ARM often unsigned, x86 often signed). signed char is explicitly signed (-128..127); unsigned char is 0..255 and the blessed type for byte buffers (may alias anything). uint8_t (where provided) is exactly 8 unsigned bits for protocols and serialization.
Byte buffers must be unsigned char (or uint8_t): plain char breaks comparisons, shifts and aliasing assumptions across platforms.
Example
#include <stdint.h> /* unsigned char raw[512]; // byte buffer: correct */ /* uint8_t pkt[64]; // protocol field: exact width */
Recommended resourcesAffiliate links · may earn us a commission