On Tue, 2014-08-12 at 20:54 +0200, Sven Joachim wrote: > On 2014-08-12 20:23 +0200, Ben Hutchings wrote: > > > On Tue, 2014-08-12 at 09:05 -0700, Steve Langasek wrote: > > [...] > >> Matthias, could you please have a look at the below test case? We have a > >> regression in the latest nfs-kernel-server build, which appears to be caused > >> by a gcc-4.9 bug. > >> > >> Should I work around this in nfs-utils, or is a quick fix possible in > >> gcc-4.9? > >> > >> > char buf[100]; > >> > > >> > void > >> > add_name(char *old) > >> > { > >> > char *cp = old; > >> > > >> > while (cp && *cp) { > >> > cp++; > >> > } > >> > __builtin_strncpy(buf, old, cp-old); > > [...] > > > > So far as I know (haven't checked the latest standard), pointer > > subtraction has undefined behaviour unless both operands point into (or > > one beyond) the same array. As this is not true of null pointers, the > > compiler may infer that old can't be null, so cp can't be null, so there > > is no need to check whether it is. > > This is true in C, unfortunately. However… > > > I.e. this is a bug in nfs-utils, not the compiler. > > …Petr's example program crashes even when compiled with g++-4.9, and in > C++ subtracting two null pointers is valid, yielding zero. Ah, I wasn't aware of that difference. The compiler might then be relying on the source argument to __builtin_strncpy() being non-null. The standard says that the pointer arguments must be pointers to arrays, which seems to make this a valid assumption. However, I suspect many programs depend on 'copying' 0 characters to or from NULL being a safe no-op (I've probably done it myself in the past). It's probably a bad idea for the compiler to assume programs don't do that. Ben. -- Ben Hutchings Humans are not rational beings; they are rationalising beings.
Attachment:
signature.asc
Description: This is a digitally signed message part