Main Content

CWE Rule 786

Access of Memory Location Before Start of Buffer

Since R2024a

Description

Rule Description

The product reads or writes to a buffer using an index or pointer that references a memory location prior to the beginning of the buffer.

Polyspace Implementation

The rule checker checks for Destination buffer underflow in string manipulation.

Examples

expand all

Issue

This issue occurs when certain string manipulation functions write to their destination buffer argument at a negative offset from the beginning of the buffer.

For instance, for the function sprintf(char* buffer, const char* format), you obtain the buffer from an operation buffer = (char*)arr; ... buffer += offset;. arr is an array and offset is a negative value.

Risk

Buffer underflow can cause unexpected behavior such as memory corruption or stopping your system. Buffer underflow also introduces the risk of code injection.

Fix

If the destination buffer argument results from pointer arithmetic, see if you are decrementing a pointer. Fix the pointer decrement by modifying either the original value before decrement or the decrement value.

Example — Buffer Underflow in sprintf Use
#include <stdio.h>
#define offset -2

void func(void) {
    char buffer[20];
    char *fmt_string ="Text";

    sprintf(&buffer[offset], fmt_string);      //Noncompliant
}

In this example, &buffer[offset] is at a negative offset from the memory allocated to buffer.

Correction — Change Pointer Decrementer

One possible correction is to change the value of offset.

#include <stdio.h>
#define offset 2

void func(void) {
    char buffer[20];
    char *fmt_string ="Text";

    sprintf(&buffer[offset], fmt_string);     
}

Check Information

Category: Memory Buffer Errors

Version History

Introduced in R2024a