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 ?
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 ?
ASKER
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 ?
Yes, no ?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
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
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
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
ASKER
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
}
}