Path: csiph.com!eternal-september.org!feeder.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Keith Thompson Newsgroups: comp.lang.c Subject: Re: UB of memcpy(NULL, NULL, 0) Date: Sun, 23 Oct 2016 14:15:00 -0700 Organization: None to speak of Lines: 30 Message-ID: References: <7aec2d7f-6f2d-4621-9f98-91947f461f27@googlegroups.com> <18bf4226-5b9a-4603-9809-47cdd83cc16a@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: mx02.eternal-september.org; posting-host="81aeb6e1d8cfc6206f4b7e00ede7a09e"; logging-data="26864"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1+UFUox3fRczpgEryaXI8YK" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.1 (gnu/linux) Cancel-Lock: sha1:fy7F2Dc3Dj7eGzkeDA8VIZ4c6qI= sha1:cMsQetfFhF/URSt4dkiPXR5Uors= Xref: csiph.com comp.lang.c:95206 Malcolm McLean writes: > On Sunday, October 23, 2016 at 8:21:43 PM UTC+1, Keith Thompson wrote: >> Meanwhile, any remaining problems can be avoided simply by *not* >> passing null pointers to memcpy(). The effort needed to do this is >> nonexistent in most cases, and minimal in all other cases. >> >> > /* > It is possible for a company to have zero employees, but it's > highly unusual. > */ > void foo(Employee *e, int Nemployees) > { > Employee *s = malloc(N * sizeof(Employee)); > > memcpy(s, e, N * sizeof(Employee)); > } > > That's the snag. This bug will lurk and could pop up at any > inconvenient moment for reasons which are hard to understand, > eg the malloc() implementation changes. Yes, the behavior of malloc(0) is implementation-defined. You need to be aware of that and allow for it. -- Keith Thompson (The_Other_Keith) kst-u@mib.org Working, but not speaking, for JetHead Development, Inc. "We must do something. This is something. Therefore, we must do this." -- Antony Jay and Jonathan Lynn, "Yes Minister"