MISRA C:2012 Dir 4.14
The validity of values received from external sources shall be checked
Description
Directive Definition
The validity of values received from external sources shall be checked.1
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:
Using an externally obtained string without a terminating null character in places where a null-terminated string is expected. Such use might result in undefined behavior. For instance, in this code, the function
printf()
expects string with a terminating null character. Using the character arraystr
, which is not terminated by a null character, results in undefined behavior.char str[10]; scanf("%10c", str); printf("%s",str);//Null terminated string expected
Using an externally obtained indeterminate string. For instance, a string might be indeterminate if you invoke an
fgets()
family function to set the value of the string but the function call fails:Because the functionchar buffer[10]; fgets(buffer, sizeof(buffer), stdin); //buffer is indeterminate if fgets() fails printf("%s",buffer); // Possible undefined behvior
printf()
expects a string with a terminating null character, usingbuffer
with this function can result in undefined behavior.
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
Check Information
Group: Code design |
Category: Required |
AGC Category: Required |
Version History
Introduced in R2017a1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.
The MISRA coding standards referenced in the Polyspace Bug Finder™ documentation are from the following MISRA standards:
MISRA C:2004
MISRA C:2012
MISRA C:2023
MISRA C++:2008
MISRA C++:2023
MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.