Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
996 views
in Technique[技术] by (71.8m points)

c - Strange behaviour when printing pointers

I have the following code:

#include <stdio.h>

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

int main(int argc, char** argv) {
  data d;
  printf("arg1: %p | arg2: %d
", d.arg1, d.arg2);
}

The output ends up being that d.arg1 is not NULL and d.arg2 is 0. For example:

arg1: 0x7fff84b3d660 | arg2: 0

When I add a pointer to main, nothing changes. However, when I print that pointer:

#include <stdio.h>

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

int main(int argc, char** argv) {
  data d;
  int* test;
  printf("arg1: %p | arg2: %d | test: %p
", d.arg1, d.arg2, test);
}

the output always results in:

arg1: (nil) | arg2: 4195264 | test: (nil)

Why am I experiencing this behaviour? I don't understand how printing another pointer value changes the value of a different pointer to NULL. Note that the compiler I am using is GCC 4.8.2.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...