I don't understand how does following code called f() function successfully.
The program has undefined behavior since b
is not initialized and is also not pointing to memory allocated by new
.
Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefined behavior. The program may just crash.
So the output that you're seeing(maybe seeing) is a result of undefined behavior. And as i said don't rely on the output of a program that has UB. The program may just crash.
So the first step to make the program correct would be to remove UB. Then and only then you can start reasoning about the output of the program.
For example, here the program doesn't crash but here it crashes.
To solve this make sure that the pointer b
is initialized and is pointing to memory allocated by new
.
1For a more technically accurate definition of undefined behavior see this where it is mentioned that: there are no restrictions on the behavior of the program.