Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Is chap9/c_inclusion.c violating the strict aliasing rule? #19

Closed
yeah-boi opened this issue Aug 4, 2017 · 2 comments
Closed

Is chap9/c_inclusion.c violating the strict aliasing rule? #19

yeah-boi opened this issue Aug 4, 2017 · 2 comments

Comments

@yeah-boi
Copy link
Contributor

yeah-boi commented Aug 4, 2017

I could be wrong, but it looks like chap9/c_inclusion.c violates the strict aliasing rule.

@sayon
Copy link
Collaborator

sayon commented Aug 4, 2017

Here is the listing itself for the reference:

#include <stdio.h>

struct parent {
    const char* field_parent;
};

struct child { 
    struct parent base;
    const char* field_child;
};

void parent_print( struct parent* this ) {
    printf( "%s\n", this->field_parent ); 
}

int main( int argc, char** argv ) {
    struct child c;
    c.base.field_parent = "parent";
    c.field_child = "child";
    parent_print( (struct parent*) &c );

    return 0;
}

I do think that this is a very good observation, because the usual list of aliasing rules does not discuss this case.

I think however that it does not violate the strict aliasing rules because it is a well-defined behavior (c11 draft, section 6.7.2.1 page 115):

15 
[...] A pointer to a structure object, suitably converted, points to its initial member [...] and vice versa.

As we are converting the pointer at the call site, it should work fine:

(struct parent*) &c

Omitting the cast issues a warning, because by default these types are not marked as compatible.

In C++, the similar thing happens when using reinterpret_cast.

@yeah-boi
Copy link
Contributor Author

yeah-boi commented Aug 5, 2017

Yes, you are correct. This issue can be closed. As you say there is a struct parent object at that memory address, so no problem since we use that same type when accessing it.

Using offsetof we could even do something similar with other fields of a struct (second, third, ...) without violating strict aliasing.

@sayon sayon closed this as completed Aug 5, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants