Warning C6053
Call to 'function' may not zero-terminate string 'variable'.
Remarks
This warning indicates that the specified function has been called in such a way that the resulting string might not be zero-terminated. This defect might cause an exploitable buffer overrun or crash. This warning is also generated if an annotated function expects a null-terminated string, but you pass a non-null-terminated string.
Most C standard library and Win32 string handling functions require and produce zero-terminated strings. A few 'counted string' functions (including strncpy
, wcsncpy
, _mbsncpy
, _snprintf
, and snwprintf
) don't produce zero-terminated strings if they exactly fill their buffer. In this case, a subsequent call to a string function that expects a zero-terminated string will go beyond the end of the buffer looking for the zero. The program should make sure that the string ends with a zero. In general, you should pass a length to the 'counted string' function one smaller than the size of the buffer and then explicitly assign zero to the last character in the buffer.
Code analysis name: MISSING_ZERO_TERMINATION1
Examples
The following sample code generates this warning:
#include <string.h>
#define MAX 15
size_t f( )
{
char szDest[MAX];
char *szSource="Hello, World!";
strncpy(szDest, szSource, MAX);
return strlen(szDest); // possible crash here
}
To correct this warning, zero-terminate the string as shown in the following sample code:
#include <string.h>
#define MAX 15
size_t f( )
{
char szDest[MAX];
char *szSource="Hello, World!";
strncpy(szDest, szSource, MAX-1);
szDest[MAX-1]=0;
return strlen(szDest);
}
The following sample code corrects this warning using safe string manipulation strncpy_s
function:
#include <string.h>
#define MAX 15
size_t f( )
{
char szDest[MAX];
char *szSource= "Hello, World!";
strncpy_s(szDest, sizeof(szDest), szSource, strlen(szSource));
return strlen(szDest);
}
Heuristics
This warning is sometimes reported on certain idioms guaranteed to be safe in practice. Because of the frequency and potential consequences of this defect, the analysis tool is biased in favor of finding potential issues instead of its typical bias of reducing noise.