开发者

What is my uninitialized struct value?

So i have two structs in the global section

typedef struct stack_1
 {
  short ctr;
 } stack_1;

typedef struct stack_2
 {
   struct stack_1 *s1;
 } stack_2;

then later in the code i do

struct stack_2 *x; 

what is my x initialized to 开发者_高级运维?? 0 or Null. Thank you in advance.


If your declaration is outside any function or with the static keyword (more precisely, has static storage duration), the initial value of x is a null pointer (which may be wrtten either as 0 or as NULL). If it's inside a function (more precisely, has automatic storage duration), its initial value is garbage.


After the local variable declaration

struct stack_2 *x; 

x is an uninitialized (dangling) pointer. It has garbage value, pointing to some random location in memory. Dereferencing it would be undefined behaviour, i.e. something you should avoid at all costs.


  • If the declaration is local , then x holds garbage value
  • If the declaration is global, then x holds 0


Since you've typedef'd the structure name you should instantiate it as follows:

stack_2 *x;

The value of x depends on where the above code is located. If it is global x will be set to 0. If it is a local variable within a function x will be uninitialized.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜