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

CWARN.BAD.PTR.ARITH

Bad pointer arithmetic

In C and C++, when doing pointer arithmetic, it is possible to accidentally refer to the wrong memory due to the way math operations are implicitly scaled. The CWARN.BAD.PTR.ARITH checker searches for instances in which a pointer has been incremented or decremented by a value that most likely was an oversight of the automatic scaling.

Vulnerability and risk

Bad pointer arithmetic can cause buffer overflow conditions.

Vulnerable code example

1  #define ARRAY_SIZE 5
2  void initialize_array()
3  {
4      int buf[ARRAY_SIZE];
5      for (int* p = buf; p < (buf + ARRAY_SIZE); p += sizeof(int)) {
6          *p = 0;
7      }
8  }

Klocwork produces a bad pointer arithmetic report for line 5 indicating that bad arithmetic is applied to pointer "p". The report here informs the reviewer that the expression p += sizeof(int) is incrementing the pointer “p” by sizeof(int) * sizeof(int) bytes (due to automatic scaling) instead of just incrementing it by sizeof(int) bytes. Thus, a buffer overflow occurs in this example.

Fixed code example

1  #define ARRAY_SIZE 5
2  void initialize_array()
3  {
4      int buf[ARRAY_SIZE];
5      for (int* p = buf; p < (buf + ARRAY_SIZE); p++) {
6          *p = 0;
7      }
8  }

The problem from the previous snippet is fixed: the pointer is increment by sizeof(int) bytes instead of sizeof(int) * sizeof(int) bytes.

Related checkers