mercredi 26 juillet 2017

Confusion with delete functionality in c++

So I wrote this code in c++

#include "ContactBook.hpp"

int main(){

    std::string name;
    ContactList *cl1 = new ContactList();

    while(true){

        std::cout << "Enter a name or press Q to quit" << std::endl;
        std::cin >> name;

        if(name=="Q"||name=="q")
            break;
        else{
            cl1->addToHead(name);
        }
    }

    cl1->print();
    delete cl1;

    return 0;
}

My header file definition ->

#ifndef ContactBook_hpp
#define ContactBook_hpp

#include <iostream>

class Contact{
    friend std::ostream &operator<<(std::ostream &os, const Contact &c);
    friend class ContactList;
public:
    Contact(std::string name);
private:
    std::string name;
    Contact* next;
};

class ContactList{
public:
    ContactList();
    void addToHead(const std::string &name);
    void print();
private:
    Contact *head;
    static int size;
};

#endif

Now here's my header files function definition. ContactList and Contact are two classes. Contact list is a friend class of Contact.

#include "ContactBook.hpp"

Contact::Contact(std::string name){
    this->name = name;
    next = NULL;
}
std::ostream &operator<<(std::ostream &os, const Contact &c){
    os << "Name: " << c.name << std::endl;
    return os;
}

ContactList::ContactList():head(NULL){};
int ContactList::size = 0;

void ContactList::addToHead(const std::string &name){

    Contact *newOne = new Contact(name);

    if(head==NULL){
        head = newOne;
    }
    else{
        newOne->next = head;
        head = newOne;
    }
    ++size;

}

void ContactList::print(){

    Contact *temp;
    temp = head;

    while(temp!=NULL){
        std::cout << *temp;
        temp = temp->next;
    }
}

The issue is whenever I add

delete newOne;

after ++size in the 3rd code snippet in addToHead definition.

I end up with an infinite loop on odd inputs of names (except 1)! I just cant understand why this is happening ! Some knowledge on this would be really appreciated :D !

Aucun commentaire:

Enregistrer un commentaire