MISRAC2012-Dir-4.14_b
In this section:
Synopsis
(Required) The validity of values received from external sources shall be checked.
Enabled by default
Yes
Severity/Certainty
Medium/Medium

Full description
A user is able to control the amount of memory used in an allocation.
Coding standards
- MISRA C:2012 Dir-4.14
(Required) The validity of values received from external sources shall be checked
Code examples
The following code example fails the check and will give a warning:
#include <stdio.h>
#include <string.h>
int main(char* argc, char** argv) {
int num;
char buffer[50];
char *other_string = "Hello World!";
gets(buffer);
sscanf(buffer, "%d", &num);
if (num > 100) return -1;
char *string = (char *)malloc(num);
strcpy(string, other_string);
}
The following code example passes the check and will not give a warning about this issue:
#include <stdio.h>
#include <string.h>
int main(char* argc, char** argv) {
int num;
char buffer[50];
char *other_string = "Hello World!";
gets(buffer);
sscanf(buffer, "%d", &num);
if (num < strlen(other_string) || num > 100) return -1;
char *string = (char *)malloc(num);
strcpy(string, other_string);
}