Programming Fundamentals · Interview question

Why is strcpy considered dangerous and what should you use instead?

A strong answer

strcpy(dst, src) copies characters from src to dst until it hits the null terminator in src, it has no way to know how big dst is, so if src is longer than dst can hold, strcpy happily writes past the end, corrupting adjacent memory. This is the classic buffer overflow that has caused thousands of security vulnerabilities. The safer modern alternatives are snprintf(dst, sizeof(dst), "%s", src), which takes the destination size as an argument and truncates instead of overflowing, or strncpy(dst, src, sizeof(dst) - 1) followed by an explicit null-terminator write (because strncpy doesn't guarantee null termination on truncation, a famous footgun in its own right). Many style guides ban strcpy outright.

What a weak answer sounds like

You know the answer. Do you know what gets you dinged?

Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.

From the lesson

Arrays & Strings

A contiguous block of same-type values. How arrays work in memory, why indexing starts at 0, and the null-terminated convention that defines C-strings.

More Arrays & Strings questions

Browse all 472 interview questions
Why is strcpy considered dangerous and what should you use instead? | EmbeddedPrep.io