Unsafe C and C++ String Functions: strcpy, strcat, gets, and sprintf (video)
Why strcpy, strcat, gets, and sprintf cause buffer overflows in C and C++, what to use instead (snprintf, std::string, bounded copies), and how to find every call in a codebase.
Transcript
Unsafe C and C++ String Functions: strcpy, strcat, gets, and sprintf. Here's the short version.
strcpy, strcat, gets, and sprintf all write into a destination buffer without knowing how large it is. If the input is longer than expected, they keep writing — past the end of the buffer and over whatever lives next to it in memory.
Why these functions are dangerous. gets reads a line of input with no length limit at all — it was removed from the C11 standard for this reason. strcpy copies until it finds a terminating null, regardless of destination size. strcat appends the same way, so the risk grows with every call. sprintf formats into a buffer with no bound, and formatted output length is easy to underestimate.
Here's an example: Fixed-size buffers and unbounded writes.
After: bounded writes or std::string. In C++, std::string manages its own size and removes the whole class of problem. In C or performance-sensitive code, use bounded functions and check the result.
Replacement cheat sheet. gets → fgets(buf, sizeof buf, stdin), or std::getline in C++. sprintf → snprintf with sizeof the destination. strcpy / strcat → std::string, or bounded copies (strncpy_s / strcat_s where available) with explicit size checks. Raw char arrays for text → std::string or std::string_view.
Want to find these issues in your own code? Connect your GitHub repository to CodeInspector. You'll get findings with the file, line, severity, and a recommended fix, plus HTML and PDF reports for your team. Start free at codeinspector.app.
More videos
- CodeInspector product demo (0:54)
- CodeInspector Now Works Inside Claude: Scan and Fix Code in One Conversation (video) (1:20)
- throw vs throw ex in C#: Why throw ex Destroys Your Stack Trace (video) (1:22)
- Thread.Sleep vs Task.Delay in C#: Which to Use and Why (video) (1:38)
- Task.Result and .Wait() Deadlocks in C#: Why Sync-over-Async Hangs (video) (1:47)
- ILogger Best Practices in .NET: Structured Logging That Helps You Debug (video) (1:20)