0

I came across a situation where I need to create a temporary object and pass it to a function. In C#, I would do something along the lines of Bar(new Foo(1, 2)); and be done with it, as C# does hold your hand a lot when it comes to memory management.

My question is, in C++, would doing the same, calling Bar(new Foo(1, 2)); create a memory leak, as new assigns memory but it is not freed (deleted) anywhere as no object is assigned to it.

Here's a sample code:

#include <iostream>

using namespace std;

struct Foo
{
    int a;
    int b;

    Foo(int a, int b)
    {
        this->a = a;
        this->b = b;
    }
};

void Bar(Foo *obj)
{
    cout << obj->a << ":" << obj->b << endl; 
}

int main(int argc, char** argv)
{
    Bar(new Foo(1, 2));

    return 0;
}

Note: I could not find a way to detect/check for memory leaks on a Windows environment (something like Valgrind on Linux), so any suggestions regarding that would be welcome! (Windows 10, g++ compiler)

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • 5
    Yes it will create a memory leak. Unlike C#, in C++ eveny piece of memory you allocated with `new`, must be deallocated with `delete`. You can use smart pointers to free yourself from having to manually manage the deallocation. – wohlstad Nov 21 '22 at 12:03
  • You can use unique pointers if you don't want memory leaks to occur as they manage allocation and deallocation automatically. – Rohan Bari Nov 21 '22 at 12:05
  • 1
    A side note: better to avoid `using namespace std` - see here https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice. – wohlstad Nov 21 '22 at 12:06
  • 3
    Yes. In C++ you generally want to avoid manually calling `new` if you really need to heap-allocate, use `std::make_unique()`. In this case, `Bar` just needs to see a `Foo`, so the signature should be `void Bar(const Foo& obj)`. Then you can call `Bar(Foo(1, 2))` and since you didn’t say `new` you don’t have to worry about `delete`ing the `Foo`. – Ben Nov 21 '22 at 12:08
  • https://youtu.be/JfmTagWcqoE – Marek R Nov 21 '22 at 12:34
  • You don't need `new` to create objects. Just do `Foo foo(1, 2); Bar(&foo);` – BoP Nov 21 '22 at 14:19
  • it by itself doesn't cause leak, you need to pair it with delete somewhere (possibly inside the function) though. – apple apple Nov 21 '22 at 16:03

0 Answers0