On Fri, 28 Dec 2007 20:43:01 -0800, Al <
Al@discussions.microsoft.com>wrote:
Quote
This is one version that I have been trying to use but the same problem
arises with other versions of similar code. I have showed below where the
errors occur.
<code>
static DWORD CALLBACK EditStreamCallBack(DWORD dwCookie, LPBYTE pbBuff, LONG
cb,
LONG *pcb)
{
CString *pstr = (CString *)dwCookie;
if( pstr->GetLength() < cb )
****
This should be <=, and it is comparing the wrong value. It MUST be
if(pstr->GetLength() * sizeof(TCHAR) <= cb)
or you will overwrite the buffer. This code was obviously written by someone who didn't
understand Unicode, and you should post a correction to the codeproject article when you
are done.
****
Quote
{
*pcb = pstr->GetLength();
<error>
****
WHAT <error>? It would have been useful to know what kind of error occurred here! When
asking questions like this, you have to show BOTH the source line (and all declarations)
AND the error message!
However, one thing is wrong with this: it is supposed to be a byte count of the number of
characters to transfer, but instead it is given as a *character* count, which is
erroneous. It should have said
*pcb = pstr->GetLength() * sizeof(TCHAR);
****
Quote
memcpy(pbBuff, (LPCSTR)*pstr, *pcb );
<error>
****
This one is obvious: it is caused by the erroneous use of LPCSTR instead of LPCTSTR. In
addition, the length is wrong; it should have been written as
memcpy(pbBuff, (LPCTSTR)*ptr, *pcb);
but note above that *pcb is erroneously computed, and until you apply the first
correction, the code as written using *pcb as the length is erroneous
*****
Quote
pstr->Empty();
}
else
{
*pcb = cb;
****
Note that this can be erroneous if cb is an odd number; to be absolutely correct, you
should make sure that this number is not an odd number in Unicode builds
****
Quote
<error>
memcpy(pbBuff, (LPCSTR)*pstr, *pcb );
<error>
****
Same problem as above: the code is not Unicode-aware, and should have been LPCTSTR
****
Quote
*pstr = pstr->Right( pstr->GetLength() - cb );
*****
For the same reasons given above, this non-Unicode-aware code is erroneous. It must be
rewritten as
*pstr = pstr->Right(pstr->GetLenght() - (cb / sizeof(TCHAR));
which is another reason you must make sure cb is an even value, and truncate downwards if
it is not.
One of the better features of VS2005 defaulting to Unicode builds is that it does not
allow the kind of sloppiness that created this code to continue. Consider the error
messages a Good Thing, they kept fundamentally incorrect code from compiling and doing
serious damage.
joe
****
Quote
}
return 0;
}
<code>
Joseph M. Newcomer [MVP]
email:
newcomer@flounder.com
Web:
www.flounder.com">
www.flounder.com
MVP Tips:
www.flounder.com/mvp_tips.htm">
www.flounder.com/mvp_tips.htm
-