C ++指针,无法读取内存

时间:2015-02-14 06:49:05

标签: c++ pointers initialization

为什么,当我启动指针时,我可以读取指定的值:

DWORD *pBytesReturned = new DWORD[0];
_result =  EnumProcesses(pProcessIds, 1000, pBytesReturned);

enter image description here

但是当我像这样初始化它时,我无法读取指定的值:

DWORD *pBytesReturned = 0;
_result =  EnumProcesses(pProcessIds, 1000, pBytesReturned);

enter image description here

如果需要,这是完整的代码:

#include "stdafx.h"
#include <Psapi.h>

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pCmdLine, int iCmdShow)
{
    bool _result;
    DWORD *pProcessIds = new DWORD[1000];
    DWORD cb;
    DWORD *pBytesReturned =0;
    _result =  EnumProcesses(pProcessIds, 1000, pBytesReturned);
}

1 个答案:

答案 0 :(得分:4)

功能的意图

BOOL
WINAPI
EnumProcesses (
    _Out_writes_bytes_(cb) DWORD * lpidProcess,
    _In_ DWORD cb,
    _Out_ LPDWORD lpcbNeeded
    );

是指针作为第三个参数,并且该指针必须指向函数将存储双字的有效内存位置。预期的函数调用应该如下所示

DWORD *pProcessIds = new DWORD[1000];
DWORD bytesReturned = 0;
bool _result = EnumProcesses(pProcessIds, 1000, &bytesReturned);

或者像这样

DWORD *pProcessIds = new DWORD[1000];
DWORD *pBytesReturned = new DWORD[1];
bool _result = EnumProcesses(pProcessIds, 1000, pBytesReturned);

但是你不应该使用NULL指针并期望调试器取消引用它。