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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With