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?
newin a function, and then hold its address in an argument of pointer, does the memory get deallocated when the function finishes?some_type * varsaysvaris a pointer to asome_type, and it is supplied by the caller. When you sayvar = ...in your function, you're just changing the local copy ofvar, causing it to forget what the caller had set it pointing to, if anything. What&does is make sure thatvarreally is the caller's actual variable, not a local copy, so when you assign tovar, you're assigning to the caller's variable.