Why it is ok to pass an uninitialized variable address to pointer paramter of a function

Viewed 242

let's say we have a C function like this,

void assign(int* refs)
{
 *refs = 123;
}

and call it in two ways

1.

int a;
assign(&a); // a is assigned a value.
int* a;
assign(a);// runtime error

I know that assign value to pointer that points to null is not ok since there is not correspond memory being allocated.
But
[1] why passing address of uninitialized variable works well?
[2] What does &a means when a hasn't been initialized.

2 Answers

The value is uninitialized, but the memory is allocated.Pointer points to memory, not to a value.

It's only a problem to read an uninitialized variable. Taking its address is fine since a variable's address is fixed for its lifetime.

In your first example you have an uninitialized variable of type int. You take its address (which is valid as above) and pass it to a function which subsequently dereferences that address to write the value of a.

In the second example, you have an uninitialized variable of type int *, but then you pass its value to the function. This is not valid because the value of the variable is indeterminate.

Related