Path: csiph.com!eternal-september.org!feeder.eternal-september.org!reader01.eternal-september.org!.POSTED!not-for-mail From: Tim Rentsch Newsgroups: comp.lang.c Subject: Re: memcpy can't take null. Date: Thu, 09 Apr 2020 07:16:02 -0700 Organization: A noiseless patient Spider Lines: 33 Message-ID: <86d08gn3rx.fsf@linuxsc.com> References: <6c3de07e-15c8-4cc0-a805-636a5976d086@googlegroups.com> <87zhbnl10s.fsf@nosuchdomain.example.com> <8338dd09-dfed-447b-adf0-356695b1b1d8@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: reader02.eternal-september.org; posting-host="bedbb4a28902cd1137b240ce253aab81"; logging-data="24593"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX19YbTfY30Y/QDXtxbVFLPhJNSZJJpuoTJA=" User-Agent: Gnus/5.11 (Gnus v5.11) Emacs/22.4 (gnu/linux) Cancel-Lock: sha1:h1LmdKSce03kE6ZPDUnn0GTUC8w= sha1:VoEXlXb64963ALsOznelPOaHc+g= Xref: csiph.com comp.lang.c:151258 Richard Damon writes: > On 4/8/20 5:06 AM, Malcolm McLean wrote: > >> If Nemployees is non-zero while the pointer employees points to invalid >> memory, it's likely that the bug will be discovered soon enough. >> But if Nemployees is zero and employees is NULL, then the loops through >> the employees array will all be no-ops and have defined, correct >> behaviour. It's only if you call a library function like memcpy that >> the code becomes incorrect. > > The issue is that since memcpy is a very basic function, you want it as > efficient as possible. On some machines, it may be quicker to load the > pointers into registers that might object to having a null pointer > before processing the loop, and thus the machine might trap on a null > pointer. > > Also, if you really want this safe version, you can make a memcpy_safe0 > function defined as: > > void* memcpy_safe0(void* dest, const void* src, size_t num) { > if(num) return memcpy(dest, src, num); > else return dest; > } > > Note, that if the library function includes the check, there is no way > to wrap it to remove that check, thus it make sense to make the standard > version the quick one. > > Note that in the above, with a decent optimizing compiler, the call to > memcpy above is tail-recursive, It is a tail call, but not a recursive tail call.