Reputation: 2307
i have a function like this
void some_func(some_type *var)
{
// do something a get a var2 of type some_type*
var = var2;
}
and in main i have
some_type *var;
some_func(var);
print_var(var);
but i get a segmentation fault when i run the program. debugging shows that print_var
is the problem, as if var
has no value. var2
is initialized using new some_type
, so i think i don't need to do this for var
.
but when i do var = new some_type
in main, and i manually clone (copy each data of var2
to var
) in some_func
, i don't get the error.
where is my problem? i am not really used to pointer and memory allocation things, but i think both ways should work. am i wrong?
maybe the main question is when i allocate a pointer using new
in a function, and then hold its address in an argument of pointer, does the memory get deallocated when the function finishes?
Upvotes: 0
Views: 95
Reputation: 5315
Your someType *var
in main()
is local to main and the *var
in the function is local to that function.
So, the var
in function is pointing to var2
but not the one which is present in main.
Upvotes: 1
Reputation: 362
You are passing var
by value. This means that a copy of var
is made on the stack, separate from the var
in main. This copy is then initialized with var2
. But, when some_func
exits, the stack is popped, and the copy is lost. The var
declared in main is unchanged.
To fix this, one possible way would be for some_func
to return a pointer value, which you can then assign to var
.
Alternately, change your declaration of some_func
to
void some_func(some_type *& var)
This passes var
by reference, meaning that, for all you are concerned, the var
in some_func
is the same as the var
in main
.
Upvotes: 1
Reputation: 1676
You need to change your definition to:
void some_func(some_type*& var)
{
// var will also be changed on the caller side
var = var2;
}
Notice that it passes a reference to a pointer so the value of the pointer can be updated by the callee.
Upvotes: 3