I want to use a function to allocate and initialize two related struct instances. However I can’t get the memory to persist outside of the allocation function. Also, I’d rather do this without memory leaks if at all possible:
void alloc_init(foo_struct *bar, foo_struct *baz){
//Create some values in here
bar = new foo_struct(created_val1, created_val2);
baz = new foo_struct(created_val3, created_val4);
}
If I check the value of created_val1 in bar from within alloc_init() it’s totally fine… But once alloc_init pops off the stack, I’m getting garbage. How do I make these kinds of values persist?
You need to pass the pointers by reference:
Because you pass your pointers by value, you’re allocating memory for copies of the original pointers inside the functions.