marc
marc

Reputation: 6223

Byte-Wise Pointer Arithmetic in sizeof(T) increments: Undefined Behaviour?

Is it undefined behaviour to perform pointer arithmetic on a pointer of type char * (that points to an int array) in increments of sizeof(int) and dereference it later? E.g. consider the code below. Does it invoke undefined behaviour?

I think the line /*1*/ should be legal, and /*2*/ is certainly legal, but I am uncertain about /*3*/.

There is a prior question that asked something similar, but has no accepted answer.

int foo() {
  int arr[10] = {0};
  int i = 4;
  int s = sizeof(int);
  /*1*/ const char * cmem = reinterpret_cast<const char*>(&arr[0]);
  /*2*/ cmem += i * s;
  /*3*/ return *reinterpret_cast<const int*>(cmem);
}

Upvotes: 1

Views: 129

Answers (1)

M.M
M.M

Reputation: 141638

This code is OK. It is permitted to do pointer arithmetic within bounds of an object (or one past the end), and the strict aliasing rule allows using an lvalue only differing in const-ness from the actual object, to access that object.

Upvotes: 3

Related Questions