Several questions about C++ STL. Thanks.

Hi, I coded a program with C++ which takes a lot of memory. I am trying to figure out why they need so much memory and therefore fix the memory problem. Listed below are some of my questions, Thank you very much for your help.

(1) code;

void funct1 (map <string, float> &m1) {
vector <string> v1;
string s;
for () {
vector <float> v2;
// operations on v1, v2, s, fill map m1...
}
// after for loop
}

My questions are: (i) Will the memory taken by v2 be released and return to OS after the for loop like int, float variables? (ii) Will the memory of v2 and s will be release and return to OS after exiting this function? (iii) after executing the function, I expect that all its related memory will be released except m1, what should I do?

(2) Is there any tool can help me tracing the memory usage of my codes? like how much memory was used before and after executing function1, how much memory was used for vector v1, etc.

Any hint will be highly appreciated. Thanks.

string and vector both use dynamically allocated memory for data storage.

This memory is freed when the object goes out of scope.

1
2
3
4
5
6
7
8
9
10
11
void funct1 (map <string, float> &m1)
{
  vector <string> v1;
  string s;
  for ()
  {
    vector <float> v2;
  } // v2 goes out of scope here, memory is freed

  // other stuff
} // v1 and s go out of scope here, memory is freed 


Note that v2 goes out of scope every loop iteration so each time the loop runs, v2 is being unallocated and reallocated which might be time consuming and might lead to memory fragmentation if it's doing a lot of reallocation.

You might want to consider moving that so it's outside the loop.


As for tools, I don't have any recommendations, sorry =x
Hi Disch,

Thanks for the info. That is very help. There is no problem to move v2 out of the loop. Another question is:

If the funct1 is initialized a lot of times (in another big loop), will that result in a lot of memory fragmentation?

Thanks very much.
it's possible, yes. Solutions to that would be to broaden the scope of those vectors... but I don't know if that's a good idea.

Basically I would only worry about it if you're having serious fragmentation issues. Otherwise this really shouldn't be a problem.
About question 2: Use a memory debugger ( http://en.wikipedia.org/wiki/Memory_debugger ) Valgrind is a common one ( and free )
Topic archived. No new replies allowed.