Strange behaviour when printing pointers

后端 未结 4 1259
执念已碎
执念已碎 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:22

    You are accessing uninitialized values. This causes undefined behaviour (meaning that anything can happen, including the program crashing).

    To fix, initialize values before using them, e.g.:

     data d = { 0 };
    
    0 讨论(0)
  • 2020-12-21 18:35

    d is uninitialized, so it can contain anything.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-21 18:44

    You should initialize d to get deterministic results:

    data d = {0, 42};
    

    or:

    data d;
    d.arg1 = 0;
    d.arg2 = 42;
    

    Without initialization, using the values leads to undefined behavior.

    0 讨论(0)
提交回复
热议问题