Last active
July 24, 2019 11:43
-
-
Save gooooloo/5777981731307f6c423a4f733be73cec to your computer and use it in GitHub Desktop.
a memory leak example in practice
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Here is an example of mem leak I met today. I didn't write the codes, I just help finding the memleak. | |
* Of course the real code is much more complicated, I simplify it here. | |
* | |
* To prove there is memleak, just compile and run: | |
* $ gcc a.cpp --std=c++11 -lstdc++ && ./a.out | |
* | |
* And you will see below: | |
* 4 bytes leaked. | |
* | |
* The interesting thing is why only 4 bytes is leaked. | |
**/ | |
#include <vector> | |
#include <queue> | |
#include <functional> | |
#include <iostream> | |
int size = 0; | |
struct A { | |
int *p = 0; | |
~A() { if (p) { delete p; size -= 4;} } | |
A &operator =(A &other) { | |
if (p) { delete p; size -= 4; } | |
p = other.p; | |
other.p = 0; | |
return *this; | |
} | |
void foo() { p = new int(3); size += 4;} | |
}; | |
void bar(A *pa) { | |
A a; | |
a.foo(); | |
*pa = a; | |
} | |
int main(int, char **) { | |
{ | |
std::queue<std::function<void (void)>> jobs; | |
const int N = 200; | |
// mem leak version | |
std::vector<A> v; | |
for (int i = 0; i < N; i++) { | |
A a; | |
jobs.emplace(std::bind(bar, &a)); | |
v.push_back(a); | |
} | |
// // ok version | |
// std::vector<A> v(N); | |
// for (int i = 0; i < N; i++) { | |
// jobs.emplace(std::bind(bar, &v[i])); | |
// } | |
while (!jobs.empty()){ | |
auto job = std::move(jobs.front()); | |
jobs.pop(); | |
job(); | |
} | |
} | |
std::cout << size << " bytes leaked." << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment