C6053

Note

This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, see Visual Studio documentation. We recommend upgrading to the latest version of Visual Studio. Download it here

warning C6053: call to <function> may not zero-terminate string <variable>

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 is passed a string that is not null terminated.

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) do not 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.

Example

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  
}  

Example

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);  
}  

Example

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);  
}  

You should note that 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.

See Also

Annotation Overview
NullTerminated
strncpy_s, _strncpy_s_l, wcsncpy_s, _wcsncpy_s_l, _mbsncpy_s, _mbsncpy_s_l