vladimir rejuk
vladimir rejuk

Reputation: 1

Unique pointer usage still memory leak, find it

#include <iostream>
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>

class My_Container
{
public:
    My_Container(int y) : x{new int(y)}
    {
        //*x = y;
    }

    int get_value() const
    {
        return *x;
    }

    bool has_value() const
    {
        return x != nullptr;
    }

private:
    std::unique_ptr<int> x = std::make_unique<int>();
};

int test1(My_Container const &container)
{
    if (container.has_value())
    {
        return container.get_value();
    }
    return -1;
}

int test2(My_Container const &container)
{
    if (container.has_value())
    {
        return container.get_value();
    }
    return -1;
}

int main()
{

    My_Container c1{5};
    My_Container const c2{3};

    std::cout << test1(c1) << std::endl;
    std::cout << test1(c2) << std::endl;

    std::cout << test2(c1) << std::endl;
    std::cout << test2(c2) << std::endl;

    _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
    _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDOUT);
    _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
    _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDOUT);
    _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
    _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDOUT);
    if (_CrtDumpMemoryLeaks())
    {
        std::cout << "he" << std::endl;
    }
    return 0;
}

5 3 5 3 Detected memory leaks! Dumping objects -> {153} normal block at 0x011D0580, 4 bytes long. Data: < > 03 00 00 00 {152} normal block at 0x011D9E30, 4 bytes long. Data: < > 05 00 00 00 Object dump complete. he

The above is the output.

Could anyone find where this memory leaks are produced in the code?

Thank you so much.

Upvotes: 0

Views: 169

Answers (1)

Mestkon
Mestkon

Reputation: 4061

_CrtDumpMemoryLeaks reports the memory as lost because c1 and c2 are still in scope. Try

int main() 
{
    {
        My_Container c1{5};
        My_Container const c2{3};

        std::cout << test1(c1) << std::endl;
        std::cout << test1(c2) << std::endl;

        std::cout << test2(c1) << std::endl;
        std::cout << test2(c2) << std::endl;
    }
    _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
    _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDOUT);
    _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
    _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDOUT);
    _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
    _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDOUT);
    if (_CrtDumpMemoryLeaks())
    {
        std::cout << "he" << std::endl;
    }
    return 0;
}

This should report no memory leaks.

Upvotes: 1

Related Questions