Buffer too small when copying string using wcsncpy_s

This C ++ code is similar to lame, but I need to support it. I can’t understand what the problem is with "too small buffer". I am using Visual Studio 2010. I will come up with the minimum code needed to reproduce based on the values ​​that I see in the debugger. Sorry, I will not check the actual fragment. Also, since my system clipboard is “busy” when I am debugging, I cannot just copy and paste, so some error may appear somewhere, but I will double check the material. Believe me, you do not want to see the whole function - it is too long to make sense :)

From tchar.h

#define _tcsncpy_s wcsncpy_s

From afxstr.h:

typedef ATL::CStringT< TCHAR, StrTraitMFC_DLL< TCHAR > > CString;

From WinNT.h:

typedef WCHAR TCHAR, *PTCHAR;

Oh man, these macros never run out. I will stay here. Finally, from the myfile.cpp file:

CString str; // Actually a function parameter with value "07/02/2010"
DWORD nIndex = 10;
DWORD nLast = 0;
LPCTSTR psz = (LPCTSTR) str; // Debugger says that it also gets "07/02/2010".

CString s;
_tcsncpy_s(
    s.GetBuffer((int) (nIndex - nLast + 1)), // I added the " + 1" part hoping to fix a bug, but that changed nothing
    nIndex - nLast,
    psz + nLast,
    (size_t) (nIndex - nLast)
);

, tcsncpy_s.inl :

  53    ...
  54    if (available == 0)
  55    {
  56        if (_COUNT == _TRUNCATE)
  57        {
  58            _DEST[_SIZE - 1] = 0;
  59            _RETURN_TRUNCATE;
  60        }
  61        RESET_STRING(_DEST, _SIZE);
=>62        _RETURN_BUFFER_TOO_SMALL(_DEST, _SIZE);
  63    }
  64    _FILL_STRING(_DEST, _SIZE, _SIZE - available + 1);
  65    _RETURN_NO_ERROR;
  66 }
  67
  68

62: _RETURN_BUFFER_TOO_SMALL. , tcsncpy_s.inl. , , ? (, ), Unicode. N ( ++ 0X , ). .

+3
3

strncpy_s - , , - , (nIndex - nLast) , (nIndex - nLast) , . (nIndex - nLast + 1), .

+1, , , strncpy_s, , . (nIndex - nLast + 1), .

+3

, wcsncpy_s(), - , , . . 1.

+3

wcsncpy_s() (http://msdn.microsoft.com/en-us/library/5dae5d43.aspx):

D- strSource strDest, D - count strSource. D- strDest ( numberOfElements) - , ; strDest [0]

Thus, the counts should be indicated in characters (elements), and not in bytes that you are already executing, and the size of the destination buffer should take into account the null terminator character that you create in the buffer but not telling wcsncpy_s()(known _tcsncpy()here) about:

_tcsncpy_s(
    s.GetBuffer((int) (nIndex - nLast + 1)), // I added the " + 1" part hoping to fix a bug, but that changed nothing
    nIndex - nLast + 1,
    psz + nLast,
    (size_t) (nIndex - nLast)
);
+2
source

Source: https://habr.com/ru/post/1753926/


All Articles