Course contentsShow
← Security
Lesson 1227 of 3,05225. Application Security - Secure CodingFree lesson

Unsafe String Functions in C/C++

Identify dangerous C functions like strcpy, strcat, sprintf, and gets that lack bounds checking and their safe alternatives.

Unsafe String Functions in C/C++

You'll learn which classic C string functions are ticking time bombs and why they're dangerous in security-critical code.

The Dangerous Legacy Functions

C and C++ inherited several string functions that lack bounds checking—they blindly copy data without verifying if the destination buffer has enough room. It's like pouring water into a glass without checking its size; eventually, it overflows.

The most notorious offenders include:

strcpy() — Copies a string without checking destination size. If the source is longer than the destination buffer, it writes past the boundary, causing buffer overflow.

strcat() — Appends strings with no length verification, creating the same overflow risk.

sprintf() — Formats strings into a buffer without bounds checking. A format string with unpredictable output length can easily overflow.

gets() — Reads input until a newline without any buffer size parameter. This function is so dangerous it was removed from C11 entirely.

The Safe Alternatives

Modern C provides safer replacements:

  • strncpy() and strncat() — Accept a maximum length parameter (though they have quirks)
  • snprintf() — Like sprintf() but with a buffer size limit
  • fgets() — Replaces gets() with explicit buffer size control

Even better, use higher-level string libraries like C++'s std::string or dedicated safe string libraries that handle memory automatically.

Why This Matters

These unsafe functions are behind countless buffer overflow vulnerabilities that attackers exploit for code execution. A single strcpy() call with untrusted input can compromise an entire system.

Key Takeaway: Avoid strcpy, strcat, sprintf, and gets in all new code—they cannot safely handle untrusted input. Always use bounded alternatives that accept explicit buffer sizes, or better yet, use memory-safe string abstractions.