VC ++ HeapAlloc里面的函数给出了空指针

时间:2012-11-21 02:58:52

标签: c++ c visual-c++ malloc heapalloc

我正在尝试使用HeapAlloc()来分配SetupDiGetDeviceRegistryProperty()使用的缓冲区。

内部GetDeviceInformation()我有:

HANDLE hHeap = GetProcessHeap();

while (SetupDiEnumDeviceInfo(DeviceInfoSet, MemberIndex++, DeviceInfoData)) 
{
    DWORD DataT;
    LPTSTR buffer = NULL;
    DWORD buffersize = 0;
    // port of device
    DWORD portnum = 0;

    GetRegistryProperty(DeviceInfoSet, DeviceInfoData, SPDRP_FRIENDLYNAME, 
         &DataT, buffer, &buffersize, &buffersize);

    if (!buffer) 
    {
        cerr << "Null Ptr!" << endl;
        exit(1);
    }
    // Do stuff, uninstall device


    if (buffer) HeapFree(hHeap, NULL, buffer); 

    }
}

GetRegistryProperty()里面我有:

void GetRegistryProperty(HDEVINFO DeviceInfoSet, PSP_DEVINFO_DATA DeviceInfoData, 
    DWORD Property, PDWORD DataT, LPTSTR buffer, PDWORD buffersize, PDWORD size)
{


    HANDLE hHeap = GetProcessHeap();

    while (!SetupDiGetDeviceRegistryProperty(
        DeviceInfoSet,
        DeviceInfoData,
        Property, //SPDRP_FRIENDLYNAME or SPDRP_CLASS
        DataT, //&DataT
        (PBYTE)buffer,
        *buffersize,
        size)) //&buffersize
    {
        if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
        {
            // Change the buffer size.
            if (buffer) HeapFree(hHeap, NULL, buffer); 

            // Double the size to avoid problems on 
            // W2k MBCS systems per KB 888609. 
            buffer = (LPTSTR)HeapAlloc(hHeap, HEAP_ZERO_MEMORY |
                HEAP_GENERATE_EXCEPTIONS, *buffersize * 2);
        }
        else
        {
            // error handling
            break;
        }
    }
}

HeapAlloc()按预期工作(缓冲区已填充属性),直到GetRegistryProperty()返回。此时,缓冲区始终为NULL。这也是预期的吗?如何返回一个char *指向一个超过创建它的函数生命周期的数组?我假设我不明白HeapAlloc()是如何工作的。

我在一个单独的函数中使用它的原因是我想用不同的GetRegistryProperty()多次调用DWORD Property。在我将代码移动到单独的函数之前,它完美地运行了。

2 个答案:

答案 0 :(得分:2)

通过引用传递buffer(注意 LPTSTR&amp; ):

void GetRegistryProperty(HDEVINFO DeviceInfoSet, PSP_DEVINFO_DATA DeviceInfoData, 
    DWORD Property, PDWORD DataT, LPTSTR& buffer, PDWORD buffersize, PDWORD size)

答案 1 :(得分:1)

您按值传递buffer,因此在GetRegistryProperty中,当您重新分配它时,只需在GetRegistryProperty中覆盖指针的副本。

将GetRegistryProperty的签名更改为:

void GetRegistryProperty(HDEVINFO DeviceInfoSet, PSP_DEVINFO_DATA DeviceInfoData, DWORD Property, PDWORD DataT, LPTSTR& buffer, PDWORD buffersize, PDWORD size)