Main Content

CWE Rule 463

Deletion of Data Structure Sentinel

Since R2023a

Description

Rule Description

The accidental deletion of a data-structure sentinel can cause serious programming logic problems.

Polyspace Implementation

The rule checker checks for Missing null in string array.

Examples

expand all

Issue

This issue occurs when a string does not have enough space to terminate with a null character '\0'.

This defect applies only for projects in C.

Risk

A buffer overflow can occur if you copy a string to an array without assuming the implicit null terminator.

Fix

If you initialize a character array with a literal, avoid specifying the array bounds.

char three[]  = "THREE";
The compiler automatically allocates space for a null terminator. In the preceding example, the compiler allocates sufficient space for five characters and a null terminator.

If the issue occurs after initialization, you might have to increase the size of the array by one to account for the null terminator.

In certain circumstances, you might want to initialize the character array with a sequence of characters instead of a string. In this situation, add comments to your result or code to avoid another review. See:

Example — Array size is too small
void countdown(int i)
{
    static char one[5]   = "ONE";
    static char two[5]   = "TWO";
    static char three[5] = "THREE"; //Noncompliant
}

The character array three has a size of 5 and 5 characters 'T', 'H', 'R', 'E', and 'E'. There is no room for the null character at the end because three is only five bytes large. This issue can cause a compilation error in C++.

Correction — Increase Array Size

One possible correction is to change the array size to allow for the five characters plus a null character.

void countdown(int i)
{
    static char one[5]   = "ONE";
    static char two[5]   = "TWO";
    static char three[6] = "THREE";
}
Correction — Change Initialization Method

One possible correction is to initialize the string by leaving the array size blank. This initialization method allocates enough memory for the five characters and a terminating-null character.

void countdown(int i)
{
    static char one[5]   = "ONE";
    static char two[5]   = "TWO";
    static char three[]  = "THREE";
}

Check Information

Category: Data Neutralization Issues

Version History

Introduced in R2023a