Why the memory do not release after funciton call?

103 views Asked by At

See my code below:

void foo() {
  std::ifstream f("data");
  string line;
  vector<string> r;
  while(getline(f, line)) {
    r.push_back(line);
  }
  f.close();
  r.resize(0);
}

int main(int argc, char *argv[])
{
  foo();
  cout << "load done" << endl;
  while(1) {;}
  return 0;
}

I use while(1) loop to check out the memory usage in htop tool, r may use 5GB RES, but after load done printed, RES still take 5GB. What's the problem?

2

There are 2 answers

0
Julian On

I think the erase and/or the clear function from vector klass would do that for you. A very good documentation for vector is also on cpusplus.com

9
2501 On

Resize doesn't guarantee that the underlying memory will be freed.

You should try with shrink_to_fit, which will reduce the capacity of the contained to fit its size.