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.
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