Does C allow pointer arithmetic?

Does C allow pointer arithmetic? For example, if we have some int*, can we add that value to another value, to get another pointer?

We can, but the spec is actually quite restrictive in what we can do. Many operations invoke undefined behavior.

First, and obviously, dereferencing a pointer to unowned memory invokes UB.

But the standard goes further: you’re not even allowed to compute a pointer to unowned memory.

Let’s say I have:

int vals[10];
int* at_vals_2  = &vals[2];  // OK
int* at_vals_9  = &vals[9];  // OK
int* at_vals_9  = &vals[9];  // OK
int* at_vals_10 = at_vals_9  + 1;  // OK
int* at_vals_11 = at_vals_10 + 1;  // UNDEFINED BEHAVIOR!!!!

The last line invokes UB, even though we never dereferenced the pointer!

Wait - why did at_vals_10 not also invoke UB? After all, vals[10] is out of bounds. The reason is that the standard allows for this specific case: computing a pointer to the point immediately after the end of an array.

I find it rather disturbing that I can invoke UB so easily. The notion of “computing” a pointer seems not quite well-defined.

Am I computing the pointer if I write:

int* at_vals_1000 = &vals[1000];

Am I computing the pointer if I write:

int* some_pointer = (int*) 10000;

Am I computing the pointer if I write:

int* at_vals_11 = false  ?  &vals[2]  :  at_vals_10 + 1;

Am I computing the pointer if I write:

int* some_pointer;

and leaving the value uninitialized?

I just released Vidrio, a free app for macOS and Windows to make your screen-sharing awesomely holographic. Vidrio shows your webcam video on your screen, just like a mirror. Then you just share or record your screen with Zoom, QuickTime, or any other app. Vidrio makes your presentations effortlessly engaging, showing your gestures, gazes, and expressions. #1 on Product Hunt. Available for macOS and Windows.

With Vidrio

With generic competitor

More by Jim

Tagged . All content copyright James Fisher 2016. This post is not associated with my employer. Found an error? Edit this page.