从注册表中获取c++崩溃的值

Get value from registry C++ crashes

本文关键字:崩溃 c++ 获取 注册表      更新时间:2023-10-16

怎么了?当我想获得AUVersion的值时,它崩溃了。此键存在于注册表中,但我无法获取。

int main(int argc, char *argv[])
{
    HKEY key;
    if (RegOpenKey(HKEY_LOCAL_MACHINE, TEXT("SOFTWARE\JavaSoft\Auto Update\"), &key) != ERROR_SUCCESS)
    {
        cout << "Unable to open registry keynn";
    }
    char path[1024];
    DWORD value_length = 1024;
//here is the crash
    RegQueryValueEx(key, "AUVersion", NULL, (LPDWORD)REG_SZ, (LPBYTE)&path, &value_length);
    cout << "the value read from the registry is: " << path << endl;

    system("pause");
    return 0;
}

第四个参数是一个LPDWORD——一个指向DWORD的指针。你把一个普通的整数转换成一个指针,这个指针(在解引用时)会崩溃。

参数接收注册表值的类型。如果您对类型不感兴趣,请将其设置为NULL。

调用RegQueryValueEx()有两个错误:

  • 类型参数必须是一个有效的地址,而不是:

    (LPDWORD)REG_SZ
    

这可能是坠机的原因。

  • &path应为path

更改为:

DWORD type;
RegQueryValueEx(key, "AUVersion", NULL, &type, (LPBYTE) path, &value_length);

您必须检查RegQueryValueEx()的结果,以确保path已被填充,并且后续代码没有处理未初始化的变量:

const DWORD result = RegQueryValueEx(key,
                                     "AUVersion",
                                     NULL,
                                     &type,
                                     (LPBYTE) path,
                                     &value_length);
// Check status of the query and ensure it was a string
// that was read.
if (ERROR_SUCCESS == result && REG_SZ == type)
{
    // Success.
}