Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!sun-barr!decwrl!ucbvax!hplabs!hpl-opus!hpnmdla!hpmwtd!jeffa From: jeffa@hpmwtd.HP.COM (Jeff Aguilera) Newsgroups: comp.lang.c++ Subject: Re: Re: references to dereferenced null pointers, etc... Message-ID: <1520025@hpmwjaa.HP.COM> Date: 15 Mar 90 22:12:42 GMT References: Organization: HP Microwave Tech. - Santa Rosa, Ca. Lines: 82 The following pointer nightmares really bother me. I am a fairly defensive programmer. So when I could not determine whether strlen() was portably defined for a null argument, I rolled my own, just to thwart unwanted surprises: ptrdiff_t myStrlen(const char* p) { register const char* q = p; if (q) while (*q) ++q; return q-p; } Alas! This is not portable. From Harbision and Steele, "C: A Reference Manual", 2nd ed, p. 166: "Given two pointers p and q of the same type, the difference p-q is an integer k such that adding k to q yields p. The type of the difference may be either int or long, depending upon the implementation. The result is well defined and portable only if the two pointers point to objects in the same array, or at least are aligned as if they did. If either of the pointers is null, the result is undefined." Undefined? Even if both are null? Does this statement really mean that char* p = 0; if (p-p != 0) ; can dump core? I bet ANSI is to blame, for their pointer paranoia. Here the solution is simple: ptrdiff_t myStrlen(const char* p) { register const char* q = p; if (q) while (*q) ++q; else return 0; return q-p; } Although it has `too many notes.' The other nightmare is implementing an efficient and portable memmove, or, equivalently, whether a given pointer aliases a member of a known array. Suppose char* p points to a malloc'ed arena of length N. Thus, p[0] through p[N-1] are valid lvalues, and generating p[N] is guaranteed not to dump core, as long as it is not accessed. How can we portably determine whether there exists a k, 0<=k