machine yearning
machine yearning

Reputation: 10119

Allocate and initialize values for structs inside of a function

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?

Upvotes: 0

Views: 319

Answers (2)

wallyk
wallyk

Reputation: 57784

You can make them static, which isn't the greatest solution. Or you can declare global variables at a higher scope, such as in a more-persistent class or global variable.

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258618

You need to pass the pointers by reference:

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);
}

Because you pass your pointers by value, you're allocating memory for copies of the original pointers inside the functions.

Upvotes: 3

Related Questions