Main Content

MISRA C++:2023 Dir 0.3.2

A function call shall not violate the function's preconditions

Since R2024b

Description

Directive Definition

A function call shall not violate the function's preconditions.

Rationale

Violating a function's preconditions can result in unexpected behavior.

For instance, the strncpy() function copies characters from a source to a destination array. The function expects the destination array to have enough memory for the copied characters. If this expectation is violated, you might see unexpected results.

Polyspace Implementation

The rule checker reports violations if the arguments to Standard Library functions do not satisfy the function preconditions. The checker supports these Standard Library functions:

  • Functions with floating point arguments such as:

    • Rounding and absolute value functions (ceil(), fabs(), floor(), and so on)

    • Division and remainder functions (fmod(), modf()

    • Functions involving exponents and logarithms (frexp(), ldexp(), sqrt(), pow(), exp(), log(), log10(), and so on)

    • Trigonometric functions (cos(), sin(), tan(), acos(), asin(), atan(), atan2(), and so on)

  • Functions with integer arguments such as:

    • Integer division functions (div(), ldiv(), and so on)

    • Absolute value functions (abs(), labs(), and so on)

  • Functions with character arguments such as:

    • Character conversion functions (toupper(), tolower(), and so on)

    • Character check functions (isalnum(), isalpha(), iscntrl(), isdigit, and so on)

  • Memory-related routines such as memcpy

  • String-related routines, such as strcpy and strncpy.

Troubleshooting

If you expect a rule violation but Polyspace® does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

The function strncpy() copies characters from a source to a destination array. A precondition for the function is that the destination array must have enough memory for the copied characters.

In this example, the first call to strncpy() is noncompliant because the destination array is not large enough to accommodate the copied characters and violates the function precondition. The second call to strncpy() is compliant because it copies just enough characters that can be accommodated in the destination array.

#include <cstring>

void copyAString(){
    char source[10] = "A string";
    char dest[5];
    strncpy(dest, source, sizeof(source)-1); //Noncompliant
}

void copyAnotherString(){
    char source[15] = "Another string";
    char dest[5];
    strncpy(dest, source, sizeof(destination)-1); //Compliant
}

Check Information

Group: Language Independent Issues
Category: Required

Version History

Introduced in R2024b