Back to Blog
critical SEVERITY8 min read

Buffer Overflow in C++: How Unsafe strcpy Puts Apps at Risk

A critical buffer overflow vulnerability was discovered and fixed in `src/display.cpp`, where unsafe C string functions were used without bounds checking. This type of vulnerability can allow attackers to corrupt memory, crash applications, or execute arbitrary code. The fix replaces unbounded functions with size-aware alternatives like `strlcpy` and `snprintf`, eliminating the overflow risk.

O
By Orbis AppSec
•Technically reviewed by Anupam Mediratta•Published May 21, 2026•Reviewed June 3, 2026

Answer Summary

A buffer overflow vulnerability (CWE-120) was found in C++ code in `src/display.cpp` where unbounded string functions like `strcpy()` were copying user-controlled or externally-sourced data into fixed-size buffers without length validation. The fix replaces all unbounded functions with size-aware alternatives (`strlcpy()`, `snprintf()`) that enforce maximum buffer sizes, preventing attackers from overwriting adjacent memory and achieving code execution or denial of service.

Vulnerability at a Glance

cweCWE-120 (Buffer Copy without Checking Size of Input)
fixReplace with size-aware alternatives (strlcpy, snprintf) that enforce maximum buffer lengths
riskMemory corruption, application crash, arbitrary code execution
languageC++
root causeUse of unbounded string functions (strcpy, strcat) without buffer size validation
vulnerabilityBuffer Overflow via Unsafe String Functions

Buffer Overflow in C++: How Unsafe strcpy Puts Applications at Risk

Vulnerability: Buffer Overflow via Unsafe C String Functions
Severity: High
File: src/display.cpp
Scanner: Semgrep (utils.custom.buffer-overflow-strcpy)
Status: ✅ Fixed


Introduction

Few vulnerability classes have as long and storied a history as the buffer overflow. First documented in the 1970s and famously weaponized by the Morris Worm in 1988, buffer overflows remain a leading cause of critical security vulnerabilities in C and C++ codebases today. Despite decades of awareness, unsafe string-handling functions like strcpy, strcat, and sprintf continue to slip into production code — sometimes in security-sensitive paths.

This post covers a real-world buffer overflow vulnerability discovered by automated static analysis in src/display.cpp and explains how a targeted, surgical fix eliminates the risk. Whether you're a C++ veteran or a developer just starting to explore native code, understanding this class of bug is essential for writing safe, resilient software.


The Vulnerability Explained

What Is a Buffer Overflow?

A buffer overflow occurs when a program writes more data into a fixed-size memory buffer than it was allocated to hold. The excess data spills into adjacent memory regions, potentially overwriting other variables, return addresses, or control data.

In C and C++, this most commonly happens with string manipulation functions that do not check how much space is available in the destination buffer before copying data.

The offending pattern in this case was the use of functions like strcpy() — or similar unbounded variants — at line 44 of src/display.cpp.

The Dangerous Functions

The C standard library provides several string functions that are notoriously unsafe:

// ❌ UNSAFE: No bounds checking — copies until null terminator
strcpy(dest, src);

// ❌ UNSAFE: No bounds checking on destination
strcat(dest, src);

// ❌ UNSAFE: No limit on output size
sprintf(buffer, "User: %s", username);

The problem with all three is the same: they trust the source data to fit in the destination. If an attacker controls the source string — through user input, a network packet, a file read, or an environment variable — they can supply a string longer than the destination buffer.

What Happens When It Overflows?

Depending on where the buffer lives in memory and what surrounds it, a buffer overflow can cause:

Outcome Description
Application crash Corrupted memory causes a segmentation fault
Data corruption Adjacent variables are silently overwritten
Control flow hijack Return addresses on the stack are overwritten, redirecting execution
Arbitrary code execution Attacker-supplied shellcode is executed with the app's privileges
Privilege escalation If the process runs as root or a privileged user, full system compromise

A Concrete Attack Scenario

Imagine display.cpp is responsible for rendering a username or display label pulled from an external source (a config file, API response, or user-supplied input):

// Somewhere in src/display.cpp (line ~44)
char display_buffer[64];
strcpy(display_buffer, user_supplied_name);  // ❌ No size check!
render_label(display_buffer);

An attacker who can influence user_supplied_name — say, by crafting a malicious configuration file or intercepting an API response — could supply a 200-character string. The first 64 bytes fill display_buffer. The remaining 136 bytes overflow into adjacent stack memory, potentially overwriting the saved return address.

When render_label returns, instead of jumping back to the legitimate caller, execution jumps to an address the attacker controls. This is the classic stack smashing attack, and it's been exploited in the wild for over 35 years.


The Fix

What Changed

The fix replaces unbounded C string functions with size-bounded alternatives that accept an explicit maximum length parameter, preventing writes beyond the buffer's allocated size.

The two primary safe replacements used in this fix are:

strlcpy instead of strcpy:

// ❌ BEFORE: Unsafe, no bounds checking
char display_buffer[64];
strcpy(display_buffer, source_string);

// ✅ AFTER: Safe, size-bounded copy
char display_buffer[64];
strlcpy(display_buffer, source_string, sizeof(display_buffer));

snprintf instead of sprintf:

// ❌ BEFORE: Unsafe formatted output
char label[128];
sprintf(label, "Display: %s", user_input);

// ✅ AFTER: Safe formatted output with explicit size limit
char label[128];
snprintf(label, sizeof(label), "Display: %s", user_input);

How the Fix Works

The key insight is simple: tell the function how big your buffer is.

  • strlcpy(dest, src, size) copies at most size - 1 characters and always null-terminates the result. No matter how long src is, dest will never overflow.
  • snprintf(dest, size, fmt, ...) writes at most size - 1 characters of formatted output. Excess output is silently truncated, but memory is never corrupted.

Using sizeof(display_buffer) rather than a hardcoded number is a deliberate best practice — if the buffer size ever changes during a refactor, the size limit automatically updates with it, eliminating a whole class of maintenance bugs.

Why This Is a Complete Fix

Some developers wonder: "Can't I just make the buffer bigger?" The answer is: no, that only delays the problem. A larger buffer is still a fixed-size buffer. An attacker can always supply a longer string. The only real fix is to enforce a hard ceiling on how much data can be written — which is exactly what strlcpy and snprintf do.


Conclusion

Buffer overflows are a solved problem — we've had the tools to prevent them for decades. Yet they persist because unsafe functions are easy to reach for, code reviews miss subtle size mismatches, and the consequences aren't always immediately visible. This vulnerability in src/display.cpp is a reminder that even experienced developers can introduce these bugs, and that automated static analysis is an essential safety net.

The fix here is clean and principled:

  1. Replace strcpy/sprintf with strlcpy/snprintf — enforce hard size limits
  2. Use sizeof(buffer) — keep size limits tied to the actual allocation
  3. Verify with a re-scan — confirm the fix is complete, not just cosmetic

More broadly, the best defense against buffer overflows is a layered one: safe-by-default language features (like std::string), compiler hardening flags, runtime sanitizers during testing, and static analysis in CI. No single layer is sufficient; together, they make this class of vulnerability extremely difficult to introduce and nearly impossible to miss.

Write code as if every string is adversarial. Because one day, it will be.


This vulnerability was automatically detected and fixed by OrbisAI Security. Automated security scanning helps teams find and fix issues like this before they reach production.

Prevention and further reading

View the Security Fix

Check out the pull request that fixed this vulnerability

View PR #11

Related Articles

critical

Aardvark.Cef.Process.Core Shared Memory Handler: Unvalidated memcpy

The shared memory handler in Aardvark.Cef.Process.Core failed to validate that the `length` parameter passed from JavaScript did not exceed the destination buffer size before calling `memcpy`. This allowed a compromised Chromium renderer process to corrupt heap memory by supplying an oversized `handle->length` value to the `openMapping` function. The fix adds explicit bounds checking using `GetArrayBufferByteLength()` before the copy operation.

high

XShmGetImage Heap Corruption: Unvalidated Image Height in streamproxy

The `XShmGetImage` function in the X11 shared memory image path copies pixel data row-by-row using `memcpy` without validating that the source image height matches the destination buffer height. An attacker or compromised server could provide an oversized source image, causing writes beyond the allocated heap buffer and triggering heap corruption or code execution.

critical

SGX Enclave ecall_store_data memcpy Buffer Overflow in 256-Byte

The Intel SGX enclave's trusted bridge functions `ecall_store_data` and `ecall_retrieve_data` used `memcpy()` to move data into and out of a fixed 256-byte `secure_storage` buffer without validating that `data_len` fit within destination boundaries. An attacker providing oversized `data_len` values could corrupt enclave memory, breaking SGX's confidentiality guarantees.

critical

How Buffer Overflow via strcpy() Happens in C++ XML Parsers and How to Fix It

A critical buffer overflow vulnerability was discovered in `buildroot-external/package/libxmlparser/xmlParser.cpp`, where the `toXMLString` function used `_tcscpy()` to write XML escape sequences into a destination buffer without any bounds checking. An attacker supplying a crafted XML document could overflow the buffer and potentially execute arbitrary code. The fix replaces all five unsafe `_tcscpy()` calls with `memcpy()` calls that copy only the exact number of bytes required for each escape

critical

How Heap Buffer Overflows Happen in C++ ZIP Extraction and How to Fix Them

A critical heap buffer overflow vulnerability was discovered in `TKLiveSync/unzip.cpp`, where ZIP archive entry names were copied into a `PATH_MAX`-sized heap buffer using `strcpy()` without any length validation. Since the ZIP specification allows entry names up to 65,535 bytes — far exceeding typical `PATH_MAX` values of 1,024 to 4,096 bytes — a crafted archive could overflow the buffer and corrupt heap memory. The fix replaces the unsafe `strcpy`/`dirname` pattern with `std::string` operation

medium

How Integer Overflow happens in C++ image processing and how to fix it

A signed integer overflow in OpenCV's `bilateralFilter.cpp` allowed the buffer size calculation `cal_width * cal_height * cn` to wrap around to a small or negative value, causing `padding.resize()` to allocate far less memory than needed. Subsequent `memcpy` operations would then write beyond the allocated buffer, creating a heap corruption primitive. The fix is a single targeted cast to `size_t` that promotes the multiplication to unsigned 64-bit arithmetic before any overflow can occur.