David
David

Reputation: 674

How to fix this memory leak in C++ project?

I have very simple code snippet:

struct simple_string
{
    simple_string(size_t size, char ch)
    : buffer_(new Buffer(std::basic_string<char, std::char_traits<char>>(size, ch).c_str(), size)) //first memory leak
    {
    }

    ~simple_string()
    {
        buffer_->release();
        delete buffer_;
    }

    struct Buffer
    {
        explicit Buffer(const char* str, size_t size)
        : str_(new char[size + 1]), //second memory leak
        count_(1)
        {
            std::char_traits<char>::copy(str_, str, size + 1);
        }

        void release()
        {
            if (this != nullptr)
            {
                --count_;

                if (count_ == 0)
                {
                    delete[] str_;
                }
            }
        }

        void acquire()
        {
            ++count_;
        }

        char* str_;
        size_t count_;
    } *buffer_;
};

int main() {
    simple_string a(3, 'a');

    return 0;
}

I don't understand, why memory leaks exist. Both raw pointers deleted in end of program life. Maybe I should not have to create pointers in initializer lists of constructors?

Upvotes: 0

Views: 252

Answers (2)

doqtor
doqtor

Reputation: 8484

I don't get memory leak using g++ 4.8.2 + valgrind 3.10.

I get it however in VS 2015 EE detecting with CRTDBG_MAP_ALLOC but that is a false positive.

Set str_ and buffer_ to nullptr after deleting pointers and then call destructor explicitly: a.~simple_string();, it will call destructor twice nothing really doing for the second time but it will show no memory leak because the first time the destructor was called before outputting the memory leaks results.

EDIT: This false positive memory leak can be work arounded (in VS2015 EE at least) by creating simple_string object in a function instead of in main():

void foo()
{
    simple_string a(3, 'a');
}

int main() 
{
    foo();

    return 0;
}

Upvotes: 2

exs
exs

Reputation: 122

Are there any issues with allocating memory within constructor initialization lists?

Try switching to real smart pointers, maybe the memory leaks you are getting are warnings instead of actual leaks at that moment?

Upvotes: 2

Related Questions