Link to home
Start Free TrialLog in
Avatar of NoobSabot
NoobSabot

asked on

Local Var

Most of the time, it's not a good idea to return a pointer / reference to a local variable.

function
    returns ptr

main
   calls function (stack memory might get corrupted)


But what about this example. Is it the same thing

struct Dlist {
    DList *prev
    DList *next
}

main {

    Dlist head;
    Dlist last(head);
    while loop {
        Dlist temp;
        last.next = temp;
        last = temp;
    }

}


The var temp goes out of scope at each end of the loop, but it's the same function. How does memory allocation work here ?
Avatar of NoobSabot
NoobSabot

ASKER

Properly written . . .

struct Rule {
    Rule *prev;
    Rule *next;
};

int main {

    Rule head = {0};
    Rule *last = &head;

    while() {
        Rule rule = {0};
        last->next = &rule;
        last = &rule;
        //cout<<temp.c_str()<<endl;
    }
}
My guess is that there shouldn't be a problem. Because the stack pointer shouldn't get modified cause we're not calling another routine?

Yes, no ?
ASKER CERTIFIED SOLUTION
Avatar of Sandra-24
Sandra-24

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I checked it manually.

w/o new - the address is always the same [bad]
w/ new - the address is always different [just gotta delete them now]

Thanks a lot
Make sure to put the

Rule rule = new Rule()

In the while loop. If it's before the while loop rule will always be the same instance of Rule. Sorry about that.

If you don't want to delete them, you have to wrap them in std::auto_ptr or some other smart pointer. You can read up on that if you like.

-Sandra