Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do the printf statements in this example invoke Undefined Behavior?

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);   
}
like image 748
ryyker Avatar asked Jun 07 '26 10:06

ryyker


1 Answers

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.

like image 115
chux - Reinstate Monica Avatar answered Jun 10 '26 02:06

chux - Reinstate Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!