简体   繁体   中英

Reference uninitialized variable in C

What happens, If I reference uninitialized variable? like,

void func(int *p)
{
  // My operation
}

int main()
{
  int a;
  func(&a);
}

What happens, If I reference uninitialized variable

func() receives the address of the variable a as defined in main() . Inside func() the pointer pa defined by func(int * pa) points to the memory holding the indeterminate value of a .

func() may assign to a by doing

*pa = 42;

which would set a to 42 .

If func() did

int b  = *pa;

it reads uninitialised memory, namely the indeterminate value of a , and this would invoke Undefined Behaviour .

From the C11 Standard (draft):

J.2 Undefined behavior

1 The behavior is undefined in the following circumstances:

[...]

  • The value of an object with automatic storage duration is used while it is indeterminate

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM