Home > Software design >  A question about dynamic memory allocation 2
A question about dynamic memory allocation 2

Time:07-31

After a few years, I discovered a memory leak bug in my code. Unfortunately the bug was not causing any issues to be noticed until I found out about it indirectly.

Below is a function addElement() from class c_string which adds a new element to a chain. My old way of doing it is like this:

class c_string
{
private:
    char *chain;
    size_t chain_total;
public:
    void addElement(char ch);
};


void c_string::addElement(char ch)
{
    char *tmpChain = new char[chain_total 1];

    for(size_t i=0;i<chain_total;i  )
        tmpChain[i] = chain[i];
    tmpChain[chain_total  ] = ch;

    delete chain;
    chain = new char[chain_total];
    chain = tmpChain;
}

I found out that by doing chain = tmpChain; I am causing a memory leak. My question is, what is the best way to handle it?

Please note, in this class I am not using any STL function, because I am simply writing my own string.

CodePudding user response:

The best way to do it is simply drop the second allocation, it serves no purpose.

void c_string::addElement(char ch)
{
    char *tmpChain = new char[chain_total 1];

    for(size_t i=0;i<chain_total;i  )
        tmpChain[i] = chain[i];
    tmpChain[chain_total  ] = ch;

    delete[] chain;
    chain = tmpChain;
}

The above is correct and even has the strong exception guarantee.

Of course even if you do not want to use std::string, std::unique_ptr would is still safer than raw new delete and you would get the rule of five for free instead of having to implement it on your own.

From performance standpoint, you might be interested in Why is it common practice to double array capacity when full? and of course std::memcpy or std::copy instead of the manual loop.

  • Related