Interview Q&A · C · 10 questions in this topic

Strings & <string.h> — C Interview Q&A

All C topics

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

Example.cc
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

Example.cc
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

Example.cc
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.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits