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? 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