Strange behaviour when printing pointers

后端 未结 4 1268
执念已碎
执念已碎 2020-12-21 18:08

I have the following code:

#include 

typedef struct {
  int* arg1;
  int  arg2;
} data;

int main(int argc, char** argv) {
  data d;
  printf         


        
4条回答
  •  误落风尘
    2020-12-21 18:39

    You are experiencing this behavior because your program invokes undefined behavior. d is uinitialized in your program and hence its value is indeterminate and this invokes undefined behavior.

    C11 6.7.9 Initialization:

    If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate.

    Quoting from this answer:

    An indeterminate value even more unspecified than unspecified. It's either an unspecified value or a trap representation. A trap representation is standards-speak for some magic value which, if you try to assign it to anything, results in undefined behavior. This wouldn't have to be an actual value; probably the best way to think about it is "if C had exceptions, a trap representation would be an exception". For example, if you declare int i; in a block, without an initialization, the initial value of the variable i is indeterminate, meaning that if you try to assign this to something else before initializing it, the behavior is undefined, and the compiler is entitled to try the said demons-out-of-nose trick. Of course, in most cases, the compiler will do something less dramatic/fun, like initialize it to 0 or some other random valid value, but no matter what it does, you're not entitled to object.

提交回复
热议问题