Main Content

CERT C: Rec. EXP08-C

Ensure pointer arithmetic is used correctly

Description

Rule Definition

Ensure pointer arithmetic is used correctly.1

Polyspace Implementation

The rule checker checks for these issues:

  • Array access out of bounds

  • Pointer access out of bounds.

  • Subtraction between pointers to different arrays.

  • Incorrect pointer scaling.

Extend Checker

A default Bug Finder analysis might not flag an Array access out of bounds issue when the input values are unknown and only a subset of inputs cause the issue. To check for the Array access out of bounds issue caused by specific system input values, run a stricter Bug Finder analysis. See Extend Bug Finder Checkers to Find Defects from Specific System Input Values.

Examples

expand all

Issue

This issue occurs when an array index falls outside the range [0...array_size-1] during array access.

Risk

Accessing an array outside its bounds is undefined behavior. You can read an unpredictable value or try to access a location that is not allowed and encounter a segmentation fault.

Fix

The fix depends on the root cause of the defect. For instance, you accessed an array inside a loop and one of these situations happened:

  • The upper bound of the loop is too large.

  • You used an array index that is the same as the loop index instead of being one less than the loop index.

To fix the issue, you have to modify the loop bound or the array index.

Another reason why an array index can exceed array bounds is a prior conversion from signed to unsigned integers. The conversion can result in a wrap around of the index value, eventually causing the array index to exceed the array bounds.

Often the result details (or source code tooltips in Polyspace as You Code) show a sequence of events that led to the defect. You can implement the fix on any event in the sequence. If the result details do not show this event history, you can search for previous references of variables relevant to the defect using right-click options in the source code and find related events. See also Interpret Bug Finder Results in Polyspace Desktop User Interface or Interpret Bug Finder Results in Polyspace Access Web Interface (Polyspace Access).

See examples of fixes below.

If you do not want to fix the issue, add comments to your result or code to avoid another review. See:

Example – Array Access Out of Bounds Error
#include <stdio.h>

void fibonacci(void)
{
    int i;
    int fib[10];
 
    for (i = 0; i < 10; i++) 
       {
        if (i < 2) 
            fib[i] = 1;
         else 
            fib[i] = fib[i-1] + fib[i-2];
       }

    printf("The 10-th Fibonacci number is %i .\n", fib[i]);    //Noncompliant
    /* Defect: Value of i is greater than allowed value of 9 */
}

The array fib is assigned a size of 10. An array index for fib has allowed values of [0,1,2,...,9]. The variable i has a value 10 when it comes out of the for-loop. Therefore, the printf statement attempts to access fib[10] through i.

Correction – Keep Array Index Within Array Bounds

One possible correction is to print fib[i-1] instead of fib[i] after the for-loop.

#include <stdio.h>

void fibonacci(void)
{
   int i;
   int fib[10];

   for (i = 0; i < 10; i++) 
    {
        if (i < 2) 
            fib[i] = 1;
        else 
            fib[i] = fib[i-1] + fib[i-2];
    }

    /* Fix: Print fib[9] instead of fib[10] */
    printf("The 10-th Fibonacci number is %i .\n", fib[i-1]); 
}

The printf statement accesses fib[9] instead of fib[10].

Issue

This issue occurs when a pointer is dereferenced outside its bounds.

When a pointer is assigned an address, a block of memory is associated with the pointer. You cannot access memory beyond that block using the pointer.

Risk

Dereferencing a pointer outside its bounds is undefined behavior. You can read an unpredictable value or try to access a location that is not allowed and encounter a segmentation fault.

Fix

The fix depends on the root cause of the defect. For instance, you dereferenced a pointer inside a loop and one of these situations happened:

  • The upper bound of the loop is too large.

  • You used pointer arithmetic to advance the pointer with an incorrect value for the pointer increment.

To fix the issue, you have to modify the loop bound or the pointer increment value.

Often the result details (or source code tooltips in Polyspace as You Code) show a sequence of events that led to the defect. You can implement the fix on any event in the sequence. If the result details do not show this event history, you can search for previous references of variables relevant to the defect using right-click options in the source code and find related events. See also Interpret Bug Finder Results in Polyspace Desktop User Interface or Interpret Bug Finder Results in Polyspace Access Web Interface (Polyspace Access).

See examples of fixes below.

If you do not want to fix the issue, add comments to your result or code to avoid another review. See:

Example – Pointer access out of bounds error
int* Initialize(void)
{
 int arr[10];
 int *ptr=arr;

 for (int i=0; i<=9;i++)
   {
    ptr++;
    *ptr=i; //Noncompliant
    /* Defect: ptr out of bounds for i=9 */
   }

 return(arr);
}

ptr is assigned the address arr that points to a memory block of size 10*sizeof(int). In the for-loop, ptr is incremented 10 times. In the last iteration of the loop, ptr points outside the memory block assigned to it. Therefore, it cannot be dereferenced.

Correction — Check Pointer Stays Within Bounds

One possible correction is to reverse the order of increment and dereference of ptr.

int* Initialize(void)
{
 int arr[10];
 int *ptr=arr;

 for (int i=0; i<=9;i++)
     {
      /* Fix: Dereference pointer before increment */
      *ptr=i;
      ptr++;
     }

 return(arr);
}

After the last increment, even though ptr points outside the memory block assigned to it, it is not dereferenced more.

Issue

This rule is raised whenever the analysis detects a Subtraction or comparison between pointers to different arrays.

Risk

This rule applies to expressions of the form pointer_expression1 - pointer_expression2. The behavior is undefined if pointer_expression1 and pointer_expression2:

  • Do not point to elements of the same array,

  • Or do not point to the element one beyond the end of the array.

Example - Subtracting Pointers
#include <stdint.h>
#include <stddef.h>

void f1 (int32_t *ptr)
{
    int32_t a1[10];
    int32_t a2[10];
    int32_t *p1 = &a1[ 1];
    int32_t *p2 = &a2[10];
    ptrdiff_t diff1, diff2, diff3;

    diff1 =  p1 - a1;   // Compliant
    diff2 =  p2 - a2;   // Compliant
    diff3 =  p1 - p2;   // Non-compliant
}

In this example, the three subtraction expressions show the difference between compliant and noncompliant pointer subtractions. The diff1 and diff2 subtractions are compliant because the pointers point to the same array. The diff3 subtraction is not compliant because p1 and p2 point to different arrays.

Issue

Incorrect pointer scaling occurs when Polyspace® Bug Finder™ considers that you are ignoring the implicit scaling in pointer arithmetic.

For instance, the defect can occur in the following situations.

SituationRiskPossible Fix
You use the sizeof operator in arithmetic operations on a pointer.

The sizeof operator returns the size of a data type in number of bytes.

Pointer arithmetic is already implicitly scaled by the size of the data type of the pointed variable. Therefore, the use of sizeof in pointer arithmetic produces unintended results.

Do not use sizeof operator in pointer arithmetic.
You perform arithmetic operations on a pointer, and then apply a cast.Pointer arithmetic is implicitly scaled. If you do not consider this implicit scaling, casting the result of a pointer arithmetic produces unintended results.Apply the cast before the pointer arithmetic.

Fix

The fix depends on the root cause of the defect. See fixes in the table above and code examples with fixes below.

If you do not want to fix the issue, add comments to your result or code to avoid another review. See:

Example - Use of sizeof Operator
void func(void) {
    int arr[5] = {1,2,3,4,5};
    int *ptr = arr;

    int value_in_position_2 = *(ptr + 2*(sizeof(int))); //Noncompliant
}

In this example, the operation 2*(sizeof(int)) returns twice the size of an int variable in bytes. However, because pointer arithmetic is implicitly scaled, the number of bytes by which ptr is offset is 2*(sizeof(int))*(sizeof(int)).

In this example, the incorrect scaling shifts ptr outside the bounds of the array. Therefore, a Pointer access out of bounds error appears on the * operation.

Correction — Remove sizeof Operator

One possible correction is to remove the sizeof operator.

void func(void) {
    int arr[5] = {1,2,3,4,5};
    int *ptr = arr;

    int value_in_position_2 = *(ptr + 2);
}
Example - Cast Following Pointer Arithmetic
int func(void) {
    int x = 0;
    char r = *(char *)(&x + 1); //Noncompliant
    return r;
}

In this example, the operation &x + 1 offsets &x by sizeof(int). Following the operation, the resulting pointer points outside the allowed buffer. When you dereference the pointer, a Pointer access out of bounds error appears on the * operation.

Correction — Apply Cast Before Pointer Arithmetic

If you want to access the second byte of x, first cast &x to a char* pointer and then perform the pointer arithmetic. The resulting pointer is offset by sizeof(char) bytes and still points within the allowed buffer, whose size is sizeof(int) bytes.

int func(void) {
    int x = 0;
    char r = *((char *)(&x )+ 1);
    return r;
}

Check Information

Group: Rec. 03. Expressions (EXP)

Version History

Introduced in R2019a

expand all


1 This software has been created by MathWorks incorporating portions of: the “SEI CERT-C Website,” © 2017 Carnegie Mellon University, the SEI CERT-C++ Web site © 2017 Carnegie Mellon University, ”SEI CERT C Coding Standard – Rules for Developing safe, Reliable and Secure systems – 2016 Edition,” © 2016 Carnegie Mellon University, and “SEI CERT C++ Coding Standard – Rules for Developing safe, Reliable and Secure systems in C++ – 2016 Edition” © 2016 Carnegie Mellon University, with special permission from its Software Engineering Institute.

ANY MATERIAL OF CARNEGIE MELLON UNIVERSITY AND/OR ITS SOFTWARE ENGINEERING INSTITUTE CONTAINED HEREIN IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT.

This software and associated documentation has not been reviewed nor is it endorsed by Carnegie Mellon University or its Software Engineering Institute.