So, I'm having a problem actually understanding memory leaks I suppose. I thought I had a grasp, but I was mistaken. Visual Leak Detector has detected 5 leaks in my code. I would post the VLD output, but it is too long. So, I will simply highlight the lines of code it says are causing leaks in the following code segments.
The first is simply in the declaration of strings.
//Get the original base filename so we can rename
// multiple files based on this.
string getOriginalFilename( char* ofilename )
string temp, result;
buffer << ofilename;
temp = buffer.str();
if( temp.substr(temp.length() - 5, 5) == ".pcap" )
buffer << temp.substr(0, temp.length() - 5);
result = buffer.str(); //MEMORY LEAK
result = temp;
The final leak is very similar to the above leak. If you guys could help me out at understanding the WHY and how of this, that would be great. The best learning tool is an example such as the ones above. Thanks in advance.
It is strange. Only leak which could happens is with ofilename c-string if you have created it using new.
In all other cases there should not be any leaks, unless standard library have them, which it should not.
The 2 lines you've kept from that segment of code completely change what is returned through result. I'm not sure if you meant for that to happen or not but the purpose of that function is to return the actual name of the file, minus any file extension, because the program later needs to append an incremented number to the end of the file as it continues to create them, ex: If the input in ofilename is "C:\filename.pcap" then it should return "C:\filename". However, I see what you are saying, that there is probably a way to do it without a stringstream. (See below)
And yes, it's been verified that the code shown, by itself, does reproduce the error. Here is an entire listing of a C++ program that creates two memory leaks.
Does the standard allocator for string use memory pooling?
Many implementations of the C++ standard libraries use their own memory pool allocators. Memory for quite a number of destructed objects is not immediately freed and given back to the OS, but kept in the pool(s) for later re-use. The fact that the pools are not freed at the exit of the program cause Valgrind to report this memory as still reachable. The behaviour not to free pools at the exit could be called a bug of the library though.
Using GCC, you can force the STL to use malloc and to free memory as soon as possible by globally disabling memory caching. Beware! Doing so will probably slow down your program, sometimes drastically.