2

I've come across a C++ library that had the following code:

void *data;
unsigned length;
...
addr = data + length

First, it does not make much sense to use void* arithmetics since the compiler will not know what is the "size" of each element (as better explained here: void * arithmetic).

However, since I've used the library with my code and it seems to work, I was wondering the following. Is this behavior deterministic in the sense that all GCC will generate the same code everytime? Or, will GCC optimize it in a heuristic way?

Community
  • 1
  • 1
rph
  • 901
  • 1
  • 10
  • 26
  • 1
    It's a GCC extension and obviously they won't change its specification. size of void will be always treated as 1. If you're planning to use another compiler...well...it's UB (but AFAIK every compiler will emit at least a warning for this) – Adriano Repetti Nov 24 '16 at 09:39
  • 1
    @acraig5075: Obviously not, this question even references that "duplicate" when explaining what this question is **not** about. – MSalters Nov 24 '16 at 09:43

1 Answers1

7

The behaviour of pointer arithmetic on a void* pointer is undefined.

GCC allows it as a non-standard compiler extension (essentially regarding void* as a char* for purposes of pointer arithmetic).

Bathsheba
  • 231,907
  • 34
  • 361
  • 483