I'm learning linked list and I have a problem with this code.
If I write line "delete add;" (***) in this code, the programme complains " Bad pointer error" with the pointer curr->name, but if i delete it, everything is ok, so do I have to delete add ?, if yes, how can I delete it?
thanks so much.
student * head = 0;
student * add = new student;
// there is now a student and 'add' knows where it is
head = add;
// now 'head' knows the location of that student too
delete add; // the student is no more
// the 'add' still has an address pointing to deallocated memory
// the 'head' still has an address pointing to deallocated memory
dereference head // kaboom
In other words, do you really want to erase the element of the list that you have just created?
Yes, there is a leak when 'ex' goes out of scope at the end of main(). It is the duty of the destructor of a List object to appropriately deallocate the resources that the object manages.