Do the printf statements in this example invoke Undefined Behavior?

对着背影说爱祢 提交于 2019-12-10 21:43:30

问题


Derived from this question...
Given the declaration in line 1 of main, are the second and third printf statements considered undefined behavior because they point to locations not owned by this process?

struct my_structure {
    int i;
};

void main() {
    struct my_structure variable = {20};
    struct my_structure *p = &variable;

    printf("NUMBER: %d\n", p++->i);  
    printf("NUMBER: %d\n", p++->i);   
    printf("NUMBER: %d\n", p++->i);   
}

回答1:


In this case, first printf() is OK per C11 6.5.6.8

printf("NUMBER: %d\n", p++->i);  

2nd p++ is undefined behavior (UB), @Osiris, as it attempts to form a pointer more than 1 past struct my_structure variable.

The rest of code is irrelevant.

//                     vvv
printf("NUMBER: %d\n", p++->i); 

Detail: the 2nd post-increment of p may occur prior to or may be deferred until after the attempted UB access (with the pre-increment p). As the increment and access are UB, either one leads to UB.




回答2:


p is made so it points to an element, which isn't different from an array of 1 element.

So accessing more than one consecutive element by incrementing p is undefined behaviour.

To be valid you'd need to point to 3 consecutive elements like:

struct my_structure variable[3];  // should be initialized too

To be complete, p++ in itself isn't the issue (the pointer points to an invalid location, so what? it's like this after most pointer loops), it's the fact that we try to read from the memory when doing p->i on an invalid location which is the problem.



来源:https://stackoverflow.com/questions/53748369/do-the-printf-statements-in-this-example-invoke-undefined-behavior

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!