CERT-STR31-C_b
In this section:
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.
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 <stdio.h>
enum { BUFFERSIZE = 32 };
void func(void) {
char buf[BUFFERSIZE];
char *p;
int ch;
p = buf;
while ((ch = getchar()) != '\n' && ch != EOF) {
*p++ = (char)ch;
}
*p = 0;
if (ch == EOF) {
/* Handle EOF or error */
}
}
The following code example passes the check and will not give a warning about this issue:
#include <stdio.h>
enum { BUFFERSIZE = 32 };
void func(void) {
char buf[BUFFERSIZE];
int ch;
size_t index = 0;
size_t chars_read = 0;
while ((ch = getchar()) != '\n' && ch != EOF) {
if (index < sizeof(buf) - 1) {
buf[index++] = (char)ch;
}
chars_read++;
}
buf[index] = '\0'; /* Terminate string */
if (ch == EOF) {
/* Handle EOF or error */
}
if (chars_read > index) {
/* Handle truncation */
}
}