CERT-STR31-C_e
Synopsis
Guarantee that storage for strings has sufficient space for character data and the null terminator.
Enabled by default
Yes
Severity/Certainty
High/High

Full description
Copying data to a buffer that is not large enough to hold that data results in a buffer overflow. Buffer overflows occur frequently when manipulating strings. To prevent such errors, either limit copies through truncation or, preferably, ensure that the destination is of sufficient size to hold the character data to be copied and the null-termination character. This check is identical to LIB-strcpy-overrun-pos.
Coding standards
- CERT STR31-C
Guarantee that storage for strings has sufficient space for character data and the null terminator
Code examples
The following code example fails the check and will give a warning:
#include <string.h>
#include <stdlib.h>
void example(void)
{
char *str1 = "Hello World!\n";
char *str2 = (char *)malloc(13);
strcpy(str2,str1);
}
The following code example passes the check and will not give a warning about this issue:
#include <string.h>
#include <stdlib.h>
void example(void)
{
char *str1 = "Hello World!\n";
char *str2 = (char *)malloc(14);
strcpy(str2,str1);
}