C++ 指针,无法读取内存
C++ Pointers, Unable To Read Memory
为什么,当我启动我的指针时,我可以读取分配的值:
DWORD *pBytesReturned = new DWORD[0];
_result = EnumProcesses(pProcessIds, 1000, pBytesReturned);
但是当我像这样初始化它时,我无法读取分配的值:
DWORD *pBytesReturned = 0;
_result = EnumProcesses(pProcessIds, 1000, pBytesReturned);
如果需要,这里是完整的代码:
#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);
}
函数的意图
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 指针并期望调试器取消引用它。
为什么,当我启动我的指针时,我可以读取分配的值:
DWORD *pBytesReturned = new DWORD[0];
_result = EnumProcesses(pProcessIds, 1000, pBytesReturned);
但是当我像这样初始化它时,我无法读取分配的值:
DWORD *pBytesReturned = 0;
_result = EnumProcesses(pProcessIds, 1000, pBytesReturned);
如果需要,这里是完整的代码:
#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);
}
函数的意图
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 指针并期望调试器取消引用它。