Corrupted printf() Results.

Hi Guys!!

I am having some trouble with the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
void Reg() {
    wchar_t value[255];
    DWORD BufferSize = sizeof(value);
 
        RegGetValue(HKEY_LOCAL_MACHINE, L"registry path here", L"TEST", RRF_RT_ANY, NULL, (PVOID)&value, &BufferSize);
       std::wcout << value << std::endl;

 char* ascii = new char[wcslen(value) + 1];
wcstombs(ascii, value, wcslen(value));

printf(ascii);

        system("pause");
	}



Now when I get the results from "printf(ascii);" the results are correct but it is followed up with jumbled data after the desired result. The console looks like this:

DOUBLE
DOUBLE═²²²²▌▌▌▌▌≥Ao▌Press any key to continue . . .

Any ideas on what I'm doing to get this result?

Many Thanks,

Googie.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <windows.h>
#include <cstdlib>
#include <cstdio>

int main()
{
    const std::size_t BUFF_SZ = 255 ;

    {
        // read reg value as normal (narrow) chars - use RegGetValueA
        // "RegGetValueA converts the stored Unicode string to an ANSI string
        // before copying it to the buffer" - MSDN
        char value[BUFF_SZ] {} ;
        DWORD buff_sz = sizeof(value); // size of the buffer
        RegGetValueA( HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", "SystemRoot",
                      RRF_RT_REG_SZ, nullptr, value, &buff_sz );
        std::cout << "value: " << value << '\n' ;
    }

    {
        // read reg value as wide chars - use RegGetValueW
        wchar_t value[BUFF_SZ] {} ;
        DWORD buff_sz = sizeof(value) ; // size of the buffer in bytes
        RegGetValueW( HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", L"SystemRoot", RRF_RT_ANY, NULL,
                      value, &buff_sz );
        std::wcout << L"value: " << value << L'\n' ; // print using wcout

        // convert wide char to narrow char and print using cstdio
        char u8_value[BUFF_SZ] {} ; // declare an array, which is large enough to store the result
        std::wcstombs( u8_value, value, BUFF_SZ ) ;
        std::printf( "%s\n", u8_value ) ;
        std::puts(u8_value) ;
    }
}


TO DO: add a check for the return value of RegGetValue to verify that it hasn't failed.
Last edited on
Topic archived. No new replies allowed.