I wrote a simple directory_iterator method in C++ to list the number of files in a given directory and noticed that when running the application the windows task manager memory usage for the application keeps increasing. I am not using any pointers so there is no free or delete[] statement in the below code.
This code snippet is part of a c++ webserver which keeps running and i noticed this issue of memory usage increase every time a directory_iterator is called. So i tried it on a stand alone application and noticed the same.
Sample code below. Visual Studio 16.9.3, C++ 17, (windows 7 pro)
#include <iostream>
#include <filesystem>
#include <conio.h>
#include <windows.h>
#include <codecvt>
std::string ws2s(const std::wstring& wstr)
{
//std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> cvt;
//return cvt.to_bytes(wstr);
if (wstr.empty()) return std::string();
int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL);
std::string strTo(size_needed, 0);
WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), &strTo[0], size_needed, NULL, NULL);
return strTo;
}
int main()
{
int counter = 0;
while (!_kbhit())
{
Sleep(1000);
for (const auto& entry : std::filesystem::directory_iterator("c:\\test"))
{
std::string fileName("");
std::string pathName("");
fileName = ws2s(entry.path().filename().wstring());
std::cout << fileName << std::endl;
}
counter++;
std::cout << counter << std::endl;
}
system("pause");
}