Export (0) Print
Expand All
Expand Minimize
This topic has not yet been rated - Rate this topic

C6053

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.

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

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.

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.