Dela via


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 — using NullTerminated property in its Pre condition — 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, one useful approach is to 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
}

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

The following code uses annotation to generate warning C6053:

#include<codeanalysis\sourceannotations.h>
using namespace vc_attributes;

void NotNullTerminatedStringReturned 
          (
           [Post(NullTerminated=No)] char* str
          )
{
  // code ...
}

void NullTerminatedStringRequired ([Pre(NullTerminated=Yes)] char* str)
{
  // code ...
}

void f (char* pC )
{
  NotNullTerminatedStringReturned(pC); //pC is not null terminated
  NullTerminatedStringRequired(pC); //requires null terminated pC
}

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

Reference

NullTerminated

strncpy_s, _strncpy_s_l, wcsncpy_s, _wcsncpy_s_l, _mbsncpy_s, _mbsncpy_s_l

Concepts

Annotation Overview