Main Content

MISRA C:2023 Dir 4.14

The validity of values received from external sources shall be checked

Since R2024a

Description

Directive Definition

The validity of values received from external sources shall be checked.

This rule comes from MISRA C™: 2012 Amendment 1.

Rationale

The values originating from external sources can be invalid because of errors or deliberate modification by attackers. Before using the data, you must check the data for validity.

For instance:

  • Before using an external input as an array index, you must check if the input can potentially cause an array bounds error.

  • Before using an external variable to control a loop, you must check if the variable can potentially result in an infinite loop.

Polyspace Implementation

The rule checker looks for these issues:

Troubleshooting

If you expect a rule violation but do not see it, refer to Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

#include <stdio.h>

void f1(char from_user[])
{
        char input [128];
        (void) sscanf (from_user, "%128c", input);
        (void) sprintf ("%s", input);/*Noncompliant*/
}

In this example, the sscanf statement is noncompliant as there is no check to ensure that the user input is null terminated. The subsequent sprintf statement that outputs the string can potentially lead to an array bounds error (buffer overrun).

In this example, the functions scanf() and fgets() read two char arrays and then print the arrays by calling printf(). Because the input strings are obtained externally, they might be indeterminate or lack a terminating null character. Printing such strings by using printf() results in undefined behavior. Polyspace® reports violations of this rule.

#include <stdio.h>
void echo_in() {
       //...
    char buffer[10];
    scanf("%10c", buffer);
	//...
    printf("%s", buffer); //Noncompliant - buffer is not null-terminated
	//...
    fgets(buffer, sizeof(buffer), stdin);
      //...
    printf("%s",buffer); //Noncompliant - buffer might be indeterminate
}

Check Information

Group: Code design
Category: Required
AGC Category: Required

Version History

Introduced in R2024a