Can I have memory leaks if I'm not using new keyword?
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?
I think it is not possible to leak memory if you do not reserve memory dynamically. Probably, global variables are not going to be freed, but I would not call that a memory leak.
However, there are more ways to dynamically reserve memory than using the keyword new
.
For example, malloc
allocates a memory block. Also calloc
reserves memory and zeroes it.
Your operating can also give you methods to manage the memory. For example strdup
for Linux.
You can also be using smart pointers and calling std::make_unique
or std::make_shared
. Both methods dynamically allocate memory.
For std::unique_ptr
you can leak if you call release()
and forget to delete the pointer.
std::make_unique<int>(3).release(); // Memory leak
For std::shared_ptr
you can leak if you create a circular reference. You can find more information here.
Also, when you use static variables, the destructor is not called when the variable goes out of scope but at the end of the execution. This is not exactly a memory leak because the destructor is finally called but you may have some memory allocated and not used.
For example, consider the following code:
#include <iostream>
#include <string>
#include <vector>
void f()
{
static std::vector<int> v;
v.insert(v.begin(), 100*1024*1024, 0);
v.clear();
}
int main()
{
f();
return 0;
}
std::vector::clear()
is not required to free the memory allocated by the vector. So, after calling f()
, you will have 400 MB of memory allocated but only accesible inside f()
. Not exactly a memory leak, but it is a resource allocated that it is not automatically freed until the end.
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.