다음을 통해 공유


C6059

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 C6059: Incorrect length parameter in call to <function>. Pass the number of remaining characters, not the buffer size of <variable>

This warning indicates that a call to a string concatenation function is probably passing an incorrect value for the number of characters to concatenate. This defect might cause an exploitable buffer overrun or crash. A common cause of this defect is passing the buffer size, instead of the remaining number of characters in the buffer, to the string manipulation function.

Example

The following code generates this warning:

#include <string.h>  
#define MAX 25  
  
void f( )  
{  
  char szTarget[MAX];  
  char *szState ="Washington";  
  char *szCity="Redmond, ";  
  
  strncpy(szTarget,szCity, MAX);  
  szTarget[MAX -1] = '\0';  
  strncat(szTarget, szState, MAX); //wrong size   
  // code ...                                   
}  

To correct this warning, use the correct number of characters to concatenate as shown in the following code:

#include <string.h>  
#define MAX 25  
  
void f( )  
{  
  char szTarget[MAX];  
  char *szState ="Washington";  
  char *szCity="Redmond, ";  
  
  strncpy(szTarget,szCity, MAX);  
  szTarget[MAX -1] = '\0';  
  strncat(szTarget, szState, MAX - strlen(szTarget)); // correct size   
  // code ...                                   
}  

To correct this warning using the safe string manipulation function, see the following code:

#include <string.h>  
  
void f( )  
{  
  char *szState ="Washington";  
  char *szCity="Redmond, ";  
  
  size_t nTargetSize = strlen(szState) + strlen(szCity) + 1;  
  char *szTarget= new char[nTargetSize];  
  
  strncpy_s(szTarget, nTargetSize, szCity,strlen(szCity));  
  strncat_s(szTarget, nTargetSize, szState,  
                    nTargetSize - strlen(szTarget));  
  // code ...  
  delete [] szTarget;  
}  

See Also

strncpy_s, _strncpy_s_l, wcsncpy_s, _wcsncpy_s_l, _mbsncpy_s, _mbsncpy_s_l
strncat_s, _strncat_s_l, wcsncat_s, _wcsncat_s_l, _mbsncat_s, _mbsncat_s_l