The string manipulation functions ``++strncat++``, ``++strlcat++`` and ``++strlcpy++`` require a size argument that describes how many bytes from the source buffer are used at most.
In many situations the size of the source buffer is unknown, which is why the size argument for these functions should be based on the size of the destination buffer.
This helps to prevent buffer overflows.
Note that ``++strncat++`` always adds a terminating null character at the end of the appended characters; therefore, the size argument should be smaller than the size of the destination to leave enough space for the null character.
[source,cpp]
----
#include <stdio.h>
#include <string.h>
void foo(const char *src) {
char dst[10] = {0};
strlcpy(dst, src, sizeof(src)); // Noncompliant: size of destination should be used.
printf("%s", dst);
}
----
== What is the potential impact?
By using the source buffer's size to determine the size argument for ``++strncat++``, ``++strlcat++`` or ``++strlcpy++``, the program becomes vulnerable to buffer overflows which pose a security risk.
To prevent potential buffer overflows, use the size of the destination buffer to determine the correct size argument for ``++strncat++``, ``++strlcat++`` and ``++strlcpy++``.
Buffer overflows occur when a program writes data beyond the boundaries of a buffer and can lead to memory corruption and potential security vulnerabilities.
Attackers can use buffer overflows to overwrite critical data, execute arbitrary code, or gain unauthorized access to a system.
To mitigate this risk, developers must carefully manage buffer sizes (, use secure coding practices, and employ techniques like input validation and bounds checking).
In {cpp}, manual string, i.e., buffer manipulations are considered a code smell.
Instead, the `std::string` type should be used to manage buffers, which guarantees safe buffer manipulations.
Instead of manually concatenating two buffers using `strncat`, for instance, `std::string` allows this operation to be performed in a much more convenient manner as shown in the following code:
In addition, the `std::format` function allows one to format strings according to a user-specified format and returns the result as a string as shown in what follows:
* CERT - https://wiki.sei.cmu.edu/confluence/display/c/STR31-C.+Guarantee+that+storage+for+strings+has+sufficient+space+for+character+data+and+the+null+terminator[STR31-C. Guarantee that storage for strings has sufficient space for character data and the null terminator]