Search code examples
c++stringmfcbuffer-overflowstrncpy

Data truncated when strncpy() used for copying string in MFC


In order to fix a buffer overflow Coverity issue, I have used strncpy() to copy a list item. The list item needs to be drag and dropped from one row to another. So the string that needs to be copied contains '\n', '\t' and ' ' characters.

I have used the below code.

for (int nColumn = 1; nColumn < nColumns; nColumn++)
{
    strncpy(lvItem.pszText, (LPCTSTR)(GetItemText(nDragIndex, nColumn)), sizeof(lvItem.pszText)-1);
    lvItem.pszText[sizeof(lvItem.pszText)] = '\0';
    lvItem.iSubItem = nColumn;
    SetItem(&lvItem);
}

The Coverity scan passed but the data in some of the columns gets truncated. I have heard of using strcpy_s method but is not available. Can anyone help me resolve issue?


Solution

  • Your code is wrong and doesn't do what you expect. lvItem.pszText is a pointer and it has a fixed size of 4 respective 8 bytes depending on the kind of your project. So your sizeof operator causes the truncation.

    Using LVITEM in this way, need a buffer that this defined by you!

    If you use GetIemText, you can also user CListCtrl::SetItemText This function takes care about all limits.