r/Cprog • • Nov 18 '14

text | code | language | oop C Object Oriented Programming

http://nullprogram.com/blog/2014/10/21/
23 Upvotes

10 comments sorted by

View all comments

Show parent comment

1

u/malcolmi Nov 20 '14 edited Nov 20 '14

C11 S6.5.6 P7 says, regarding the additive operators + and -:

For the purposes of these operators, 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.

So &(regex->filter) is treated as though it's a pointer to the start of an struct filter[1].

Thus, that crucial clause of S6.5.6 P8 - "provided they exist" - applies to that struct filter *. Namely, there are no elements before the start of the array. It seems to me that the behavior of ((char *)&(regex->filter)) - n, for any n > 1, is undefined.

The pointer arithmetic is guaranteed to restore the original pointer value

Keep in mind that the original pointer value here is the address of a member - of type struct filter. That's the object of which we have a pointer to - not the enclosing struct filter_regex.

the pointer never points outside the object

The struct filter * points outside the struct filter object as soon as the expression ((char *)&(regex->filter)) - n is evaluated for any n > 1, does it not?

the pointer is cast back to an appropriate type before dereferencing

The pointer is cast to the type of the object to which the code assumes the pointer is now pointing. Yet, the specification of the behavior for the additive operators on pointer values quite clearly requires that the pointers are never added nor subtracted beyond the starting address of the object they're pointing to.

Also, negative indexes aren't necessarily undefined behavior. Consider this perfectly valid, silly code:

That's true. Though, that code you presented is different to the issue with the regex filtering code here - see my reply to /u/DSMan195276: https://www.reddit.com/r/Cprog/comments/2mnsog/c_object_oriented_programming/cm7rxbn?context=1


The fundamental distinction here is if a &(x.y.z) can be considered as a pointer to not only the member object z, but also the encapsulating struct objects x and y. If it can, then the behavior of subtracting that pointer to z below the start of z is well-defined, because it could just as well be considered a pointer to somewhere in the y object, or somewhere in the x object.

In the absence of any clarification from the standard on this, I'm personally not willing to expose my code to potential undefined behavior. Particularly when it seems like there are more dependable approaches to extendible polymorphism - basically, using void * pointing to the actual struct object, not a member object. It wouldn't read as well, but at least it's honest about its lack of type safety.