Undefined behavior: when attempting to access the result of function call

前端 未结 3 666
粉色の甜心
粉色の甜心 2020-12-19 04:39

The following compiles and prints \"string\" as an output.

#include 

struct S { int x; char c[7]; };

struct S bar() {
    struct S s = {42,          


        
3条回答
  •  死守一世寂寞
    2020-12-19 05:18

    The sequence point occurs at the end of the full expression- i.e., when printf returns in this example. There are other cases where sequence points occur

    Effectively, this rule states that function temporaries do not live beyond the next sequence point- which in this case, occurs well after it's use, so your program has quite well-defined behaviour.

    Here's a simple example of not well-defined behaviour:

    char* c = bar().c; *c = 5; // UB
    

    Here, the sequence point is met after c is created, and the memory it points to is destroyed, but we then attempt to access c, resulting in UB.

提交回复
热议问题