ARTICLE AD BOX
I have a code to write a string to a MMF and read it
This code run perfectly in debug profile, but not in release profile.
#include <iostream> //for cout #include <regex> //split + to_string #include <windows.h> //MMF + GetModuleFileName #define BUF_SIZE 256 HANDLE hMapFile; LPCWSTR pBuf; //LPCSTR LPCWSTR szName; #include <tchar.h> //pour utiliser _tcslen bool init_error = false; int get_TCHAR_length(std::string str) { size_t size = str.length(); TCHAR* wArr = new TCHAR[size + 1]; //wArr[size] = '\0'; return (_tcslen(wArr) * sizeof(TCHAR)); } TCHAR* convert_string_to_TCHAR(std::string str) { size_t size = str.length(); TCHAR* wArr = new TCHAR[size + 1]; for (size_t i = 0; i < size; ++i) wArr[i] = str[i]; wArr[size] = '\0'; return wArr; } std::string convert_wstring_to_string(std::wstring wstr) { std::string str(wstr.begin(), wstr.end()); return str; } std::string convert_LPCWSTR_to_string(LPCWSTR l) { std::wstring ws(l); //convert to wstring std::string str = convert_wstring_to_string(ws); //convert to string return str; } void MMF_write(LPCWSTR _pBuf, std::string str) { CopyMemory((PVOID)_pBuf, convert_string_to_TCHAR(str), get_TCHAR_length(str)); } std::string MMF_read(LPCWSTR _pBuf) { return convert_LPCWSTR_to_string(_pBuf); } int main() { init_error = false; std::string s = "xxxxxx_"; s = s + "454545" + "_mmf_" + "1"; std::wstring stemp = std::wstring(s.begin(), s.end()); szName = stemp.c_str(); //MMF hMapFile = CreateFileMapping( INVALID_HANDLE_VALUE, // use paging file NULL, // default security PAGE_READWRITE, // read/write access 0, // maximum object size (high-order DWORD) BUF_SIZE, // maximum object size (low-order DWORD) szName); // name of mapping object if (hMapFile == NULL) { std::cout << "Could not create file mapping object" << std::endl; init_error = true; } else { pBuf = (LPCWSTR)MapViewOfFile(hMapFile, // handle to map object //LPCSTR FILE_MAP_ALL_ACCESS, // read/write permission 0, 0, BUF_SIZE); if (pBuf == NULL) { std::cout << "Could not map view of file" << std::endl; CloseHandle(hMapFile); init_error = true; } } if (init_error == true) { std::cout << "Could not create MMF" << std::endl; return 0; } std::string str = "#PORT#"; str = str + "11111" + "#" + "22222" + "#END#"; std::string _result = ""; int j = 0; for (int i = 0; i < 10000; i++) { MMF_write(pBuf, str); _result = MMF_read(pBuf); std::cout << "MMF: " << _result << " (" + std::to_string(j) + ")" << std::endl; if (_result == str) break; j = j + 1; } }Result in debug profile :
MMF: #PORT#11111#22222#END# (0)Result in release profile :
MMF: #PORT#11111# (974) MMF: #PORT#11111# (975) MMF: #PORT#11111# (976) ... MMF: #PORT#11111# (9998) MMF: #PORT#11111# (9999)Compile on MSVC 2022 and C++14.
All options are default.
I already tried to disable optimization.
Could someone help me to understand this VS2022 behavior?
Or maybe I got errors in my code?
