C++ Vector Memory Release introduces how to release vector memory in C++
, but the example only involves 1-dimension vector. I write a small application to verify freeing 2-dimension vector (the OS is OpenBSD
) :
#include <unistd.h>
#include <vector>
#include <iostream>
using namespace std;
int main(void) {
vector<vector<char>> vec(1024 * 1024, vector<char>(1024));
cout << "Before freeing memory, sleep 30 seconds ..." << endl;
sleep(30);
vector<vector<char>>().swap(vec);
cout << "Sleep now ..." << endl;
sleep(300);
return 0;
}
Use clang++
to build and run it:
# clang++ -std=c++11 free.cpp
# ./a.out
(1) When “Before freeing memory, sleep 30 seconds ...
” is printed, checked the memory usage of program:
We can see the program occupied more than 1G
memory.
(2) After “Sleep now ...
” is outputted, the memory usage began to descend, and when it became stable, the memory program consumed is only aboutĀ 19K
:
P.S., the full code isĀ here.