<story><title>Passing nothing is surprisingly difficult</title><url>https://davidben.net/2024/01/15/empty-slices.html</url></story><parent_chain></parent_chain><comment><author>kazinator</author><text>There is no problem with memcpy other than that you can&amp;#x27;t use a null pointer. You can memcpy zero bytes as long as the pointer is valid. This works in a good many circumstances; just not circumstances where the empty array is represented by not having an address at all.&lt;p&gt;For instance, say we write a function that rotates an array: it moves the low M bytes to the top of the array, and shuffles the remaining M - N bytes down to the bottom. This function will work fine with the zero byte memmove or memcpy operations in the special case when N == 0, because the pointer will be valid.&lt;p&gt;Now say we have something like this:&lt;p&gt;&lt;pre&gt;&lt;code&gt;  struct buf {
    char *ptr;
    size_t size;
  };
&lt;/code&gt;&lt;/pre&gt;
we would like it so that when the size is zero, we don&amp;#x27;t have an allocated buffer there. But we&amp;#x27;d like to support a zero sized memcpy in that case: memcpy(buf-&amp;gt;ptr, whatever, 0) or in the other direction likewise.&lt;p&gt;We now have to check for buf-&amp;gt;ptr being buf in the code that deals with resizing.&lt;p&gt;Here is a snag in the C language related to zero sized arrays. The call malloc(0) is allowed to return a null pointer, or a non-null pointer that can be passed to free.&lt;p&gt;oops! In the one case, the pointer may not be used with a zero-sized memcpy; in the other case it can.&lt;p&gt;This also goes for realloc(NULL, 0) which is equivalent to malloc(0).&lt;p&gt;And, OMG I just noticed ...&lt;p&gt;In C99, this was valid realloc(ptr, 0) where ptr is a valid, allocated pointer. You could realloc an object to zero.&lt;p&gt;I&amp;#x27;m looking at the April 2023 draft (N3096). It states that realloc(ptr, 0) is undefined behavior.&lt;p&gt;When did that happen?</text></comment>
<story><title>Passing nothing is surprisingly difficult</title><url>https://davidben.net/2024/01/15/empty-slices.html</url></story><parent_chain></parent_chain><comment><author>cbarrick</author><text>Useful context on the Rust side is this issue [1]. It sounds like some of the author&amp;#x27;s concerns are addressed already.&lt;p&gt;[1]: &lt;a href=&quot;https:&amp;#x2F;&amp;#x2F;github.com&amp;#x2F;rust-lang&amp;#x2F;unsafe-code-guidelines&amp;#x2F;issues&amp;#x2F;472&quot;&gt;https:&amp;#x2F;&amp;#x2F;github.com&amp;#x2F;rust-lang&amp;#x2F;unsafe-code-guidelines&amp;#x2F;issues&amp;#x2F;4...&lt;/a&gt;</text></comment>