== How to fix it

Insecure functions should be replaced with safer alternatives that limit how much data can be written to the buffer.

=== Code examples

==== Noncompliant code example

[source,cpp,diff-id=1,diff-type=noncompliant]
----
#include <stdio.h>

char str[20];
gets(str); // Noncompliant; `str` buffer size is not checked and it is vulnerable to overflows
----

[source,cpp,diff-id=2,diff-type=noncompliant]
----
#include <string.h>

char buffer[20];
strcpy(buffer, input); // Noncompliant; `input` length is not checked and it may overflow `buffer`
----


==== Compliant solution

[source,cpp,diff-id=1,diff-type=compliant]
----
#define __STDC_WANT_LIB_EXT1__
#include <stdio.h>

char str[20];
gets_s(str, sizeof(str));
----

[source,cpp,diff-id=2,diff-type=compliant]
----
#define __STDC_WANT_LIB_EXT1__
#include <string.h>

char buffer[20];
strcpy_s(buffer, sizeof buffer, input);
----

=== How does this work?

C and {cpp} have a number of functions that are considered insecure because they do not perform bounds checking. Functions like ``gets`` are known to be risky. Replace these with safer alternatives that include bounds checking. For example, instead of ``gets``, use ``gets_s``.

The code can also checks if the size of input data is less than or equal to the size of a buffer (including the terminating null byte when dealing with strings).

The ``++gets_s++`` function is defined in annex K of C11 and is optional for C11 compilers. It will only be available if the macro ``++__STDC_LIB_EXT1__++`` is defined, and it must be enabled by defining the macro ``++__STDC_WANT_LIB_EXT1__++`` before including ``++<stdio.h>++``.

Other platform-specific functions can perform the same operations. For example, ``++strcpy++`` can be substituted with https://learn.microsoft.com/en-us/windows/win32/api/strsafe/nf-strsafe-stringcbcopya[StringCbCopyA] (Windows) or https://www.freebsd.org/cgi/man.cgi?query=strlcpy[strlcpy] (FreeBSD).
