Home > Backend Development > C++ > body text

Is Pointer Arithmetic on Non-Array Pointers with `reinterpret_cast` Undefined Behavior?

Patricia Arquette
Release: 2024-11-08 15:12:01
Original
1067 people have browsed it

Is Pointer Arithmetic on Non-Array Pointers with `reinterpret_cast` Undefined Behavior?

Is Pointer Arithmetic with Non-Array Pointers Undefined Behavior?

The C standard specifies that adding or subtracting an integral expression to a pointer results in a pointer of the same type. However, if the pointer originally points to an element within an array, the resulting pointer must also point to a valid element within the array. This raises the question: is it undefined behavior (UB) to add to a "char *" pointer that doesn't actually point to a character array?

Consider the following code:

struct Foo {
    float x, y, z;
};

Foo f;
char *p = reinterpret_cast<char *>(&f) + offsetof(Foo, z); // (*)
*reinterpret_cast<float *>(p) = 42.0f;
Copy after login

Line () performs a reinterpret_cast to convert the address of f to a "char " pointer and then adds the offset of the z member. The resulting pointer p is used to modify the value of f.z.

According to the standard, this line should result in UB because p does not point to a character array. However, it is commonly assumed that it is permissible to use such pointers to manipulate the underlying memory representation of objects.

The standard does not explicitly state that this is UB, but it requires that objects of trivially copyable types can be copied into an array of char or unsigned char. This suggests that pointer arithmetic should be defined for pointers to the raw bytes that make up an object, allowing for the above operation.

Therefore, it is reasonable to conclude that adding to a "char *" pointer that doesn't point to a character array is not UB in scenarios where the underlying bytes are intended to be copied into an array.

The above is the detailed content of Is Pointer Arithmetic on Non-Array Pointers with `reinterpret_cast` Undefined Behavior?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template