Search code examples
c++pointersvectordestructordelete-operator

Delete pointer to vector of char* in destructor (Not working)


I have a class that holds a few vectors, I'm not sure which method is the best but when the I call the destructor they should be deleted from memory.

HEADER:

class Test
{
public:
    Test();
    ~Test();

    void AddString(char* text);
    void AddString(string text);

private:
    char * StringToCharPointer(string value);

    vector<char*> *pVector;
}

CPP File:

Test::Test()
{
};

Test::~Test()
{
    vector<char*>::iterator i;

    for ( i = pVector->begin() ; i < pVector->end(); i++ )
    {
        delete * i;
    }

    delete pVector;
};

char * Test::StringToCharPointer(string value)
{
    char *pChar = new char[value.length()];
    strcpy(pChar, value.c_str());

    return pChar;
};

Test::AddString(char* text)
{
    pVector->push_back(text);
};

Test::AddString(string text)
{
    pVector->push_back(StringToCharPointer(text));
};

so here's pretty much all the methods that I use, but what's wrong?


Solution

  • Firstly, i is an iterator on the vector, it is not the pointer stored in the vector. *i is the pointer stored in the vector, so if you're going to delete anything it should be that.

    Secondly, delete *i is only valid if the object pointed to by *i was allocated with new. Not new[], not malloc, and it doesn't point to a string literal. Since you don't say how your data was allocated, it is not possible for us to say whether or not you are freeing it correctly.

    It seems likely that you should use a std::vector<std::string>.

    Update for updated question:

    HEADER:

    class Test
    {
    public:
        Test();
        ~Test();
    
        void AddString(const string &text);
    private:
        vector<string> mVector;
    };
    

    CPP file:

    Test::Test()
    {
    };
    
    Test::~Test()
    {
    };
    
    void Test::AddString(const string &text)
    {
        mVector.push_back(text);
    };