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.UNBOUND_SPRINTF

Buffer overflow from unbound sprintf

The function sprintf is used to write formatted output to a buffer of memory. The function has a fixed size array as a destination, but sprintf doesn't impose limits on the output data, so there is potential for buffer overflow.

The SV.STRBO.UNBOUND_SPRINTF checker looks for code that calls sprintf.

Vulnerability and risk

The function sprintf does not check the length of the string being output and can easily result in a buffer overrun. It is preferable, if possible, to use the snprintf function and review the usage of buffers in the application.

Vulnerable code example

1  int main()
2  {
3       char fixed_buf[10];
4       sprintf(fixed_buf,"Very long format string\n"); 
5       return 0;
6  }

Klocwork produces an issue report at line 4 indicating that function sprintf doesn't check buffer boundaries and may overrun buffer fixed_buf of fixed size 10.

Fixed code example

1  int main()
2  {
3       char fixed_buf[23];
4       char *pointer_buf;
5       strcpy(fixed_buf, "Something rather large");
6       strcpy(pointer_buf, "Something very large as well");
7  
8       return 0;
9  }

In the fixed code example, the size of fixed_buf has been increased to 23 to make sure that it has enough room for the sprintf operation. Another option for fixed code is to use snprintf and check the buffer size.