4 ms·
> and then promptly uses pointer arithmetic to create an alias. It violated the promise. afaik not creating aliased pointers is not a promise you make when mar
by dthul 4y ago
> and then promptly uses pointer arithmetic to create an alias. It violated the promise.
afaik not creating aliased pointers is not a promise you make when marking a pointer as restrict. Only when using that aliased pointer for accesses (in the presence of modifications) can you actually break the promise. To quote cppreference:
"During each execution of a block in which a restricted pointer P is declared (typically each execution of a function body in which P is a function parameter), if some object that is accessible through P (directly or indirectly) is modified, by any means, then all accesses to that object (both reads and writes) in that block must occur through P (directly or indirectly), otherwise the behavior is undefined"
- xscott 4y ago> Only in the presence of accesses and modifications can you actually break the promise. Ok, creating aliases you don't use is probably fine. I should've worded that more carefully. However, the example code certainly modifies the same piece of memory from two different pointers, and so it broke the promise.
- dthul 4y agoYes, I think it boils down to whether creating a derived pointer from a restrict pointer and then using both is allowed. I just had a look at the C standard and I think it is allowed if the derived pointer is (what the standard calls) "based" on the restrict pointer (page 89, 6.7.3.1 paragraph 3: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2310.pdf http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2310.pdf). The standard language is very dense but it makes it sound like the program presented in the article would not uphold this "based" property and so might be UB as you suspected.
- ralfj 4y agoThe standard defines "based on" by talking about hypothetical alternative executions where the original value has a different value. In those executions, the access in question does not even happen in my program. What this goes to show is that the definition in the standard is ill-formed -- this can happen because the standard is written in English rather than a formal, mathematical language. However, I think it is quite clear that the intention of the standard is to allow my program. It would certainly allow the alternative where the `if (xaddr == y2addr) {` is removed and its body (then-branch) put directly into the main function. It makes no sense to disallow this program just because it introduces an extra condition, ergo I claim this program has defined behavior.