Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

A question about dynamic memory allocation 2

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.
If you want to know more asked a question about it here: https://stackoverflow.com/?newreg=4b839ccb32864d4ca199e32714120a10

bellow there is a function addElement from a class c_string that adds a new element to chain. My old way of doing it is:

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 what is the best way to do it?
Please remember in this class i am not using any STL function, because I am simply writing my own string.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thank you for reading

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading