Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I have memory leaks if I'm not using new keyword?

I'm new to the language and I have a basic doubt about memory leaks. Is it possible to have a leak if I don't use the new keyword? (i.e having my variables in the stack and using data containers like std::vector)

Should I worry about this issue?

If that is the case, can someone give me an example of a situation that creates a leak without dynamically allocating memory?

like image 618
MonkeyCoder Avatar asked Jan 23 '19 22:01

MonkeyCoder


2 Answers

i.e having my variables in the stack and using data containers like std::vector

No, with std::vector or other standard containers you shouldn't have to worry.

can someone give me an example of a situation that creates a leak without dynamically allocating memory?

One popular mistake are circularly dependent smart pointers of the form:

class Child;
class Parent {
     std::vector<std::shared_ptr<Child>> childs;
};

class Child {
     std::shared_ptr<Parent> parent;
};

Since the reference counters of the shared pointers will never drop to zero those instances never would be deleted and cause a memory leak.

More info about what causes that and how to avoid it can be found here

  • How to avoid memory leak with shared_ptr?
like image 176
πάντα ῥεῖ Avatar answered Nov 03 '22 15:11

πάντα ῥεῖ


In addition to the other answers, an easy source for memory leaks are external libraries. A lot of them, especially C or C-like libraries, have functions like create_* and destroy_* for their data types. Even though you never explicitly call new, it is still just as easy to have a memory leak.

like image 33
sudgy Avatar answered Nov 03 '22 14:11

sudgy