Learn more about Russian war crimes in Ukraine.

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?

What can computers do? What are the limits of mathematics? And just how busy can a busy beaver be? This year, I’m writing Busy Beavers, a unique interactive book on computability theory. You and I will take a practical and modern approach to answering these questions — or at least learning why some questions are unanswerable!

It’s only $19, and you can get 50% off if you find the discount code ... Not quite. Hackers use the console!

After months of secret toil, I and Andrew Carr released Everyday Data Science, a unique interactive online course! You’ll make the perfect glass of lemonade using Thompson sampling. You’ll lose weight with differential equations. And you might just qualify for the Olympics with a bit of statistics!

It’s $29, but you can get 50% off if you find the discount code ... Not quite. Hackers use the console!

More by Jim

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