Home > Backend Development > C++ > body text

Is Adding to a 'char *' Pointer Undefined Behavior When It Doesn't Point to an Array?

Linda Hamilton
Release: 2024-11-10 14:41:02
Original
469 people have browsed it

Is Adding to a

Adding to a "char *" Pointer: UB or Not?

C 17 defines rules for adding integral expressions to pointers, stating that undefined behavior results when the result exceeds the bounds of a pointed-to array. However, the definition pertains specifically to pointers pointing to elements of arrays.

Consider the following code snippet:

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

The question arises whether line (*) triggers undefined behavior. Despite reinterpreting the address to a float as a char pointer, it does not point to a char array. Thus, according to the cited definition, it would seem to be undefined behavior. Yet, the usefulness of the offsetof macro would be severely compromised if that were the case.

However, C also allows copying the underlying bytes of any trivially copyable type into a character array. This operation, which can be performed using functions like std::memcpy or manually byte by byte, does not require the original object to be an array.

Consequently, to allow these byte-wise operations to succeed, the addition of integral expressions to pointers must be defined for pointers pointing to the raw bytes of objects. Whether these bytes implicitly form an array or constitute a special exception to general addition rules is unclear. Nonetheless, either interpretation would justify the validity of the addition in the provided code example. Therefore, adding to a "char *" pointer in this context does not incur undefined behavior.

The above is the detailed content of Is Adding to a 'char *' Pointer Undefined Behavior When It Doesn't Point to an Array?. 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