Home > Net >  when is pointer to one past the last element of a memory area valid for pointer arithmetic?
when is pointer to one past the last element of a memory area valid for pointer arithmetic?

Time:09-12

The C standard says there is a pointer to "one past the last element of the array object" , which is valid for purposes of pointer arithmetic (you can do pointer arithmetic and get expected results).

My question is, what exactly is meant by "array object", so that "one past" pointer is valid for arithmetic? Something declared as array of elements of a type, is an array object.

What else?

Is pointer to character after the area returned from malloc(), (edit) cast to char* , guaranteed to be valid for arithmetic?

Is pointer to character after the area returned from mmap(), (edit) cast to char* , guaranteed to be valid for arithmetic?

I can't find any confirmation in man pages of these functions.

CodePudding user response:

An array type describes a contiguously allocated nonempty set of objects with a particular member object type, called the element type. The element type shall be complete whenever the array type is specified. Array types are characterized by their element type and by the number of elements in the array. An array type is said to be derived from its element type, and if its element type is T, the array type is sometimes called "array of T". The construction of an array type from an element type is called "array type derivation". (6.2.5, 23)

An object is defined as:

region of data storage in the execution environment, the contents of which can represent values Note 1 to entry: When referenced, an object can be interpreted as having a particular type (3.15)

void * specifically does not support arithmetic (UB), so that would rule out malloc and mmap. If you assign or cast it an array of something then it's fair game.

@ChrisDodd pointed out that:

For the purposes of these operators [ed: *, , -], a pointer to an object that is not an element of an array behaves the same as a pointer to the first element of an array of length one with the type of the object as its element type. (6.5.6, 8)

  •  Tags:  
  • c
  • Related