0

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");
}
wdcruz
  • 1
  • 1
  • 1
    Lots of errors, here's one: error C4996: 'std::wstring_convert,wchar_t,std::allocator,std::allocator>': warning STL4017: std::wbuffer_convert, std::wstring_convert, and the header (containing std::codecvt_mode, std::codecvt_utf8, std::codecvt_utf16, and std::codecvt_utf8_utf16) are deprecated in C++17 – StureS Apr 08 '21 at 14:00
  • Yup! Doesn't compile. – Devolus Apr 08 '21 at 14:02
  • changed the ws2s method using a windows specific method based on https://stackoverflow.com/questions/215963/how-do-you-properly-use-widechartomultibyte, i had earlier disabled 4996 so my example compiled. This code now compiles without the 4996 error. The reason for using ws2s is that there are some file names with asian characters. – wdcruz Apr 08 '21 at 14:51

0 Answers0