Can't figure out what's wrong with my delete function. If I remove the delete for the name and address it works as expected, but am I not leaking memory that way?
Structs:
struct Person
{
char* name;
char* address;
int zipcode;
};
struct Node
{
Person* per; // Person structure from earlier problem
Node* prev; // address of the Node previous to this one
Node* next; // address of the Node after this one
};
struct NodeList
{
Node* head;
Node* tail;
int size;
};
Init a Node:
Node * newNode = new Node;
Init(newNode);
void InitNode(Node * node)
{
// Declare and initialize new Person
Person * tempPerson = new Person;
// prompt user for new Person
cout << "NEW NODE" << endl;
_flushall(); // Cant get anything other than this to work
ClearInputStream(); //Portable input clear (but doesn't work)
char buffer[80+1]; // Initialize Char buffer for Person Name
cout << "Name: ";
cin.getline(buffer, 80);
tempPerson->name = new char[strlen(buffer)+1]; // Assign memory for new Name
strcpy(tempPerson->name, buffer); // Update name
_flushall();
ClearInputStream();
char buffer2[80+1]; // Initialize Char buffer for Person Address
cout << "Address: ";
cin.getline(buffer2, 80);
tempPerson->address = new char[strlen(buffer)+1]; // Assign memory for new Address
strcpy(tempPerson->address, buffer2); // Update address
int zip; // Declare Int for zip code
cout << "Zip: ";
cin >> zip;
tempPerson->zipcode = zip; // Update zipcode
node->per = tempPerson; // Update Person for Node
return;
}
Deleting a node
DeleteNode(node);
delete node;
void DeleteNode(Node * node)
{
//Person * tempPerson = node->per;
//Comment out the next 2 lines and it works, but leaking memory?
delete node->per->address; // ERROR!
delete node->per->name; // ERROR
delete node->per; // Works
return;
}