Pointers - Is it safe to point to invalid memory?

Ali Çehreli acehreli at yahoo.com
Mon Aug 18 02:42:42 UTC 2025


On 8/17/25 8:05 AM, Paul Backus wrote:

 > In C, it is UB to *create* an out-of-bounds pointer, *except* for a
 > pointer that is one element past the end of an array, which is allowed.
 > (Source: [C11 § 6.5.6 ¶ 8][1]) The intent of this exception is to allow
 > idioms like the one above.
 >
 > In D, merely *creating* an out-of-bounds pointer is never UB. In
 > general, D tries to avoid making things UB unless it is absolutely
 > necessary to do so, and that is probably why D is less strict than C 
here.
 >
 > In both C and D, it is always UB to *dereference* an out-of-bounds 
pointer.
 >
 > [1]: https://port70.net/~nsz/c/c11/n1570.html#6.5.6p8

That's exactly my understanding. If a C library has a function like the 
following,

   void foo(T* beginning, T* one_past_the_end);

and since D is allowed to call C functions, I would call that C function 
like this:

   // Expected in D:
   T[] arr;
   foo(arr.ptr, arr.ptr + length);  // Second argument is pointing outside

I claim the call is valid and that D's spec is missing an explicit 
mention to allow this.

Otherwise, I would have to make the following in D, which would be 
ridiculous:

   // Ridiculous in D:
   T[] arr;
   auto larger_arr = new T[arr.length + 1];
   larger_arr[0..$ - 1] = arr[];
   foo(larger_arr.ptr, larger_arr.ptr + length);

I still like the book. ;) The spec needs improvement.

Ali



More information about the Digitalmars-d-learn mailing list