FYI: CListBox gotcha!
I ran into an interesting 'bug' today. It isn't really a bug, but it's caused
by an easy-to-make mistake, and the results are pretty disasterous.
Here's a sample of some code using CListBox::GetText:
MyDlg::MyFunc(int iIndex)
{
CString sListBoxItemText ;
m_CListBoxFoo.GetText( iIndex, sListBoxItemText ) ;
…
}
The GetText function is defined as:
_AFXWIN_INLINE void CListBox::GetText(int nIndex, CString& rString)
const
{ GetText(nIndex,
rString.GetBufferSetLength(GetTextLen(nIndex))); }
NOTE: If you ever pass an invalid index to this function, or something else
goes wrong internally, GetTextLen will return LB_ERR (-1). This will be passed
into CString::GetBufferSetLength, which asserts in debug mode, but goes on in
either case. The -1 value is then used to set the data length, and as an array
index within the CString object… Although I haven't seen this crash, I'm
pretty sure a little further manipulation of that CString object would yield
some horrible results.
This isn't technically a bug, since MyFunc() should have validated iIndex, but
it's an easy mistake to make, and most list box APIs/messages are set up to
deal with a -1 index passed in. It may also be possible to pass in a perfectly
good index, but get an LB_ERR return on the GetTextLen call, in which case this
could be considered a real bug.
-Scott