Start here

Home
About Klocwork
What's new
Fixed issues
Release notes
Installation

Reference

C/C++ checkers
Java checkers
C# checkers
MISRA C 2004 checkers
MISRA C++ 2008 checkers
MISRA C 2012 checkers
MISRA C 2012 checkers with Amendment 1
Commands
Metrics
Troubleshooting
Reference

Product components

C/C++ Integration build analysis
Java Integration build analysis
Desktop analysis
Refactoring
Klocwork Static Code Analysis
Klocwork Code Review
Structure101
Tuning
Custom checkers

Coding environments

Visual Studio
Eclipse for C/C++
Eclipse for Java
IntelliJ IDEA
Other

Administration

Project configuration
Build configuration
Administration
Analysis performance
Server performance
Security/permissions
Licensing
Klocwork Static Code Analysis Web API
Klocwork Code Review Web API

Community

View help online
Visit RogueWave.com
Klocwork Support
Rogue Wave Videos

Legal

Legal information

SV.STRBO.BOUND_SPRINTF

Buffer overflow from bound sprintf

The function snprintf is used to write formatted output to a buffer of memory. Among its parameters is a pointer to the output parameter and the maximum number of bytes to write to the output buffer, including the null termination byte. The size parameter must be less than or equal to the number of bytes allocated in the output buffer. If the size parameter is greater than the size of the output buffer, a buffer overflow may result.

The SV.STRBO.BOUND_SPRINTF checker looks for code that calls snprintf using an array of fixed size as the output buffer and in which the size parameter is greater than the known size of the buffer.

Vulnerability and risk

If the snprintf function is called with a size parameter that is greater than the size of the output buffer, a buffer overrun error can result. This can lead to application instability or, with a carefully constructed attack, code injection, or other vulnerabilities.

Vulnerable code example

1  void foo(const char *src)
2  {
3     char buf[20];
4     snprintf(buf, 40, "%s", src);
5  }

Klocwork produces an issue report at line 4 because the size parameter given to snprintf is 40, which is greater than the size of the output buffer 'buf', 20. The size parameter in the snprintf function must be less than or equal to the number of bytes allocated in the output buffer, so if the string in 'src' is equal to or greater than 20 in length in this case, it will result in a buffer overflow.

Fixed code example

1  void foo(const char *src)
2  {
3     char buf[20];
4     snprintf(buf, sizeof(buf), "%s", src);
5  }

In the fixed code example, the sizeof(buf) parameter is used to avoid specifying a size greater than the size of the output buffer.