Lets say i have a class TwoWayList that holds Records , and GetRec actually creates a new list on the heap, here is the method
void GetRec(TwoWayList<Record> &rec)
{
TwoWayList<Record>* list= new TwoWayList<Record>();
Record r;
list->Insert(&r);
}
Now i have the follow two scenarios, the first one dies when i call delete, and the other one i just get a null reference to record, so when i call MoveToStart() i get a segfault, however if i just delete it works…
int main () {
TwoWayList<Record> record;
GetRec(record);
record.MoveToStart();
delete &record;//crash
return 0;
}
int main () {
TwoWayList<Record> *record;
GetRec(*record);
record->MoveToStart(); //segfault
delete record;
return 0;
}
So whats going on here? Im creating a TwoWayList in the heap in the method, therefore shouldnt i be able to delete (in fact wont it be a leak if i dont delete it?) Whats the correct way to get the TwoWayList from the method here in order for me to be able to delete it later?
Thanks
Daniel
Your first
maincreates record on the stack — not the heap. So your attempt todeletethe address of a stack variable crashes.Your second
mainnever allocatesrecordat all. So when you try to use the pointer, it segfaults.Also, your function allocates memory, but then forgets about it and leaks it. By that I mean that you create a new
list, but never hold onto the pointer. Once the function exits, you no longer have a pointer to the list you created — probably not what you wanted to do.GetRecalso ignores the input parameter — also probably not what you wanted.Guessing at what you’re attempting…
This creates a TwoWayList (named record), passes a reference to record to the function GetRec. GetRec creates a Record and Inserts it into the TwoWayList. Back in
main, it calls MoveToStart on record (which now has one Record inserted into it).This avoids any issues with new/delete by using the stack, at the cost copying Record when you insert it into the TwoWayList. It’s doubtful the performance cost of that copy will matter much to you. But if it does, just say so.