Pointer arithmetic on pointers to variably-modified types

With the following code (godbolt)

#include <stddef.h>

ptrdiff_t f(size_t n, void *x, void *y)
    if (!n) return 0;
    typedef unsigned char type[n];
    type *a = x, *b = y;
    return a - b;

and -Werror=pointer-arith clang loudly complains about

<source>:7:14: error: subtraction of pointers to type 'type' (aka 'unsigned char [n]') of zero size has undefined behavior [-Werror,-Wpointer-arith]
    return a - b;
           ~ ^ ~

while gcc compiles the code without complaint.

What is the undefined behavior that clang thinks is occuring? The possibility of the subtraction being zero and therefore not a valid pointer to an element of the array or something different? There's no array access being performed, right? So that shouldn't be the case...

If the code does exhibit undefined behavior, is there a simple way to modify the code to be fully conforming?

I'm actually trying to use this kind of construct in a function contract ala qsort and bsearch, taking a void * to an array, an array length, an element size, and a function that works on elements of the array.

My motivation is to simplify the pointer arithmetic involved by having a variably-modified type do all the work for me.

Read more here: https://stackoverflow.com/questions/64949298/pointer-arithmetic-on-pointers-to-variably-modified-types

Content Attribution

This content was originally published by nebel at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: