ptr
is passed to funcn
by value so the parameter ptr
only gets the copy of ptr
in main
. Any changes to func
's ptr
would not modify main
's ptr
and hence memory is not allocated for the pointer ptr
in main
. The assignment to uninitialized pointer
*ptr = 2;
invokes undefined behavior.
Possible solutions:
Using pointer to pointer:
void func(int** ptr)
{
*ptr = new int;
}
int main()
{
int* ptr;
func(&ptr);
*ptr = 2;
}
Returning pointer from function:
int* func(int* ptr)
{
ptr = new int;
}
int main()
{
int* ptr;
ptr = func(ptr);
*ptr = 2;
}
Using reference:
void func(int&* ptr)
{
ptr = new int;
}
int main()
{
int* ptr;
func(ptr);
*ptr = 2;
}