Re: TCHAR and buffer overflows

From: David Hopwood (
Date: 08/26/02

Date: Mon, 26 Aug 2002 17:38:28 +0000
From: David Hopwood <>


Edward Elliott wrote:
> David Hopwood wrote:
> > Edward Elliott wrote:
> >>WCHAR buf[256];
> >>strncpy(buf, src, sizeof(buf));
> >
> > I think you mean TCHAR (WCHAR always represents a UTF-16 code unit).
> > strncpy treats the first zero byte in the source string as terminating
> > the string, so it simply doesn't work for copying UTF-16 strings. Anyway,
> > it will cause a compiler warning due to incompatible types.
> Again, entirely my fault, I tried to adapt the example without thinking
> it through. The important point is the sizeof expression provides an
> incorrect value, which can be passed to any function expecting a length.
> > IME, the skills required to write secure internationalised code are just
> > those required to write internationalised code, plus those required to
> > write secure code. As long as you're doing both correctly, there are no
> > hidden gotchas in the interaction between them.
> You don't think the sizeof(buf) expression is confusing?

No, I don't. It gives the size of an object in bytes (for the C Standard
definition of "byte"). It does not give the number of elements in an array.
You *have* to understand this in order to have any chance of writing
correct C code that uses sizeof.

> It looks perfectly valid until you realize the elements of buf are not
> necessarily length 1. I confess I saw nothing wrong with the code the
> first time until the bug was explained to me.
> In any case, my point has nothing to do with secure internationalized
> code. I was demonstrating why passing pointers plus lengths to
> functions like strncpy won't automatically eliminate buffer overflows.

Of course it won't. My complaint was only with your example.

- --
David Hopwood <>

Home page & PGP public key:
RSA 2048-bit; fingerprint 71 8E A6 23 0E D3 4C E5 0F 69 8C D4 FA 66 15 01
Nothing in this message is intended to be legally binding. If I revoke a
public key but refuse to specify why, it is because the private key has been
seized under the Regulation of Investigatory Powers Act; see

Version: 2.6.3i
Charset: noconv