Test of freeing 2-dimension vector memory in C++

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:

1

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:

2

P.S., the full code is here.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.