Reputation: 1445
I've found unexpected results about memory management running the following (sample) code:
#include <stdint.h>
#include <iostream>
#include <vector>
#define BIGNUM 100000000
// sample struct
struct Coordinate {
uint64_t x;
uint64_t y;
uint64_t z;
Coordinate() {
x = 1ULL;
y = 2ULL;
z = 3ULL;
}
};
int main() {
std::vector<Coordinate*>* coordinates = new std::vector<Coordinate*>();
for (int i = 0; i < BIGNUM; ++i)
coordinates->push_back(new Coordinate());
// block 1
for(std::vector<Coordinate*>::iterator it = coordinates->begin(); it != coordinates->end(); ++it)
delete(*it);
// block 2
delete(coordinates);
std::cout << "end\n";
std::cin.get();
return 0;
}
On my Ubuntu 14.04:
The command ps aux --sort -rss was performed on std::cin.get();
4 times, with small differences:
1) program as is
2) with block 1 commented (basically no delete on every vector's element)
3) with block 2 commented (so no delete on vector)
4) both both blocks 1 and 2 commented.
With my (big) surprise test 1) and 2) have almost the same RSS / VSZ results. In simple words it seems that delete(*it);
doesn't work properly (doesn't free memory). Same conclusion can be achieved with 3) and 4).
On Windows XP (running in VirtualBox) everything is fine and memory is 0-2 MB running the program as is.
Upvotes: 0
Views: 103
Reputation: 385395
Just because delete
frees memory doesn't mean that the memory is immediately released back to the operating system for general use. Memory management on modern OSes is just not that simple.
There's nothing wrong here other than your assumptions!
Upvotes: 3