1

I have the following 2 dimension vector:

std::vector<std::vector<int>> m_scoreVector; 

I try the following code to free the allocated memory. But, it does not work. Just a small portion of memory will be releases:

for (int k = 0; k < m_scoreVector.size(); ++k){     
    std::vector<int>().swap(m_scoreVector[k]);
    m_scoreVector[k].shrink_to_fit();   
    m_scoreVector[k].clear();
}

std::vector<std::vector<int>>().swap(m_scoreVector);
m_scoreVector.shrink_to_fit();
m_scoreVector.clear();

I am new to memory management. Please let me know how should I free the allocated memory for this vector. Thanks.

icedwater
  • 4,701
  • 3
  • 35
  • 50
Bipario
  • 221
  • 1
  • 4
  • 14
  • 2
    It's freed for you. It's really that simple. – chris Jun 19 '13 at 04:20
  • It is not! At each run, this vector gets 2000 KB but it only frees 200 KB! – Bipario Jun 19 '13 at 04:23
  • 1
    How are you determining how much memory is being used? – Vaughn Cato Jun 19 '13 at 04:23
  • I am debugging the program and checking the Task Manager! – Bipario Jun 19 '13 at 04:24
  • Is there any way to completely remove it? – Bipario Jun 19 '13 at 04:25
  • 3
    @Bipario Try running your piece of code that you suspect may have a memory leak 10,000, 100,000 or 1,000,000 times. Then if there's a memory leak you'll know because it will add up that much. – Patashu Jun 19 '13 at 04:32
  • @ Patashu: Thanks for your answer. But I did and it really is not any memory leak ! I am so confused! – Bipario Jun 19 '13 at 04:36
  • 1
    @Bipario, Look up RAII. That's how we roll. – chris Jun 19 '13 at 04:39
  • @Bipario This might shed some light on your confusion - *There is more than one way to ask 'How much memory is a process using?' and they all mean very different things.* http://stackoverflow.com/questions/1984186/what-is-private-bytes-virtual-bytes-working-set – Patashu Jun 19 '13 at 04:40

2 Answers2

0

Vectors manage the memory for you. They will free the memory when they go out of scope. In general, if you don't allocate memory with new or malloc, you don't need to worry about freeing it either.

bdwain
  • 1,665
  • 16
  • 35
0

swap() and shrink_to_fit() are two ways to free vector memory,you can not use it together

try this code:

for (int k = 0; k < m_scoreVector.size(); ++k){     
    m_scoreVector[k].clear();
    m_scoreVector[k].shrink_to_fit();   
}
m_scoreVector.clear();
m_scoreVector.shrink_to_fit();
hongyang
  • 63
  • 2
  • 5
  • I tried `m_scoreVector.clear(); m_scoreVector.shrink_to_fit();` without that for loop,it works the same. – hongyang Sep 24 '18 at 03:45