Hello, I encountered a problem displaying data in the console when using the method with the RegQueryValueEx function. When extracting data from main (if you directly call a function) everything is displayed correctly. But if you place the function in the method, the cracks are displayed.

I want to make a universal method to access the registry. When cout is called in the body of the method, the data is also displayed normally, as soon as they are output. Cout in main is displayed nonsense. Most likely this is due to the encoding of the console itself, but I’m not sure and ask you for help. Wednesday VS2015.

Fragment of the latest version with the Registry class:

ER_CODE Registry::GetOsVersion(HKEY mainKey, LPCTSTR keyPath, LPCTSTR keyValue, LPSTR &registryData) { HKEY key; DWORD regtype; DWORD reg; TCHAR data[256]; if (RegOpenKeyEx(mainKey, keyPath, NULL, KEY_READ, &key) == ERROR_SUCCESS) { if (RegQueryValueEx(key, keyValue, NULL, &regtype, (LPBYTE)&data, &reg) == ERROR_SUCCESS) { if (regtype == REG_SZ) { registryData = data; RegCloseKey(key); return SUCCESS; } else return WARNING; } else return WARNING; } else return WARNING; } int main() { LPTSTR regData; ER_CODE eCode; Registry reg; eCode = reg.GetOsVersion(HKEY_LOCAL_MACHINE,TEXT("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion"), TEXT("ProductName"), regData); if (eCode == SUCCESS) { printf("%-20s\n",regData); } system("pause"); return NULL; } 

    1 answer 1

    data is a local variable, as it exits the function, it ceases to exist. assignment of the form registryData = data; copies only the pointer, but not the data itself. Therefore, in the line printf("%-20s\n",regData); you have a pointer to garbage (more precisely, the pointer value itself has not changed, but the memory where it points to could have been rubbed).

    What to do?

    It is necessary to allocate memory more correctly. If there are two ways, either allocate memory directly to main and pass a pointer to this memory ( char data[256] is also a memory allocation, not necessarily malloc or new). Also, it's a good idea to transfer the size of this allocated memory into a function, so that it knows it.

    The second way is that the function itself allocates memory, but then you need to remember to free the memory yourself.

    • The third way is to use std::string - Pavel Mayorov
    • There is one problem with this method. The code uses TCHAR, but for some reason Microsoft did not make the type tstring. and it comes in handles ... - KoVadim
    • one
      So this is all simple. You just have to forever abandon single-byte strings. - Pavel Mayorov
    • Thanks for the answer. Deal with the problem - Fiuw