On Thu, 2009-01-29 at 13:00 +0100, Sven-Ola Tuecke wrote:
[...]
> strncpy has a serious sematic flaw which makes it easy to invent bugs. I'm 

The world is full of pitfalls. If $PROGRAMMER doesn't know what a
function/sys-call/... does, he/she better learn it or doesn't use it at
all.
Anything else will lead sooner than later to bugs - even on OpenBSD with
strlcpy(), snprintf() and all of the other s little less dangerous
functions.

The main problem is: it doesn't solve the problems which strlcpy()
solves but it was there long before (AFAIK before I started to learn C
which is > 20 years ago).
And to be more exact, strncpy() has 2 major (design) flaws (which are
both fixed by strlcpy() BGTW):
- it doesn't guarantee a terminating '\0'
- it always writes n bytes.
  That may be irrelevant for 20 byte buffers but if one allocates e.g.
  larger buffers (a few KB), strncpy() forces lots of L1/L2-cache
  writebacks of '\0' bytes (which are almost never read anyways) and
  cache misses afterwards which can seriously hurt performance.
  Especially if some over-paranoid people startto copy strings around
  because it's easier, doens't need review, avoids "const" on function
  parameters or some other insane reason.

Valid uses of strncpy() is where one wants to make sure to erase the
whole buffer to not leak information. This may mainly be the case within
kernels but may be relevant in user-space libraries too.
So one can't really forbid strncpy() as such.

> used to think "memcpy" instead of "strncpy" - which is normally the right 
> thing to think[tm]. Better use something like this:
Better not.
> #if paranoid-about-runtime
> #define strcpy(d, s) (d[sizeof(d) - 1] = 0, strncpy(d, s, sizeof(d) - 1))
> #endif
Which trivially fails if "d" is a pointer.

[ fullquote deleted ]

	Bernd
-- 
Firmix Software GmbH                   http://www.firmix.at/
mobil: +43 664 4416156                 fax: +43 1 7890849-55
          Embedded Linux Development and Services




