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.