Rule A27-0-2 (advisory, implementation, automated)
A C-style string shall guarantee sufficient space for data and the null terminator.
Rationale
To prevent buffer overflows, it needs to be ensured that the destination is of sufficient size to hold the character data to be copied and the null terminator. Note that C-style string requires additional space for null character to indicate the end of the string, while the C++ std::basic_string does that implicitly. Note: This rule is deliberately redundant, in case the rule A27-0-4 is disabled in a project.
Example
// $Id: A27-0-2.cpp 289436 2017-10-04 10:45:23Z michal.szczepankiewicz $
#include <iostream>
#include <string>
void F1() noexcept
{
char buffer[10];
std::cin >> buffer; // Non-compliant - this could lead to a buffer overflow
}
void F2() noexcept
{
std::string string1;
std::string string2;
std::cin >> string1 >> string2; // Compliant - no buffer overflows
}
void F3(std::istream& in) noexcept
{
char buffer[32];
try
{
in.read(buffer, sizeof(buffer));
}
catch (std::ios_base::failure&)
{
// Handle an error
}
std::string str(buffer); // Non-compliant - if ’buffer’ is not null
// terminated, then constructing std::string leads
// to undefined behavior.
}
void F4(std::istream& in) noexcept
{
char buffer[32];
try
{
in.read(buffer, sizeof(buffer));
}
catch (std::ios_base::failure&)
{
// Handle an error
}
std::string str(buffer, in.gcount()); // Compliant
}
See also
SEI CERT C++ [10]: STR50-CPP. Guarantee that storage for strings has sufficient space for character data and the null terminator.