在运行末尾列出的代码时,我在最后一行FREE(pTcpTable);
处得到一个休息,如果我继续这个错误显示:
" netMon.exe中0x7737096E (ntdll.dll)的未处理异常:0xC0000005:访问违反读取位置0x00000009。"
crt0date .c打开,显示如下代码:
void __cdecl __crtExitProcess (
int status
)
{
__crtCorExitProcess(status);
/*
* Either mscoree.dll isn't loaded,
* or CorExitProcess isn't exported from mscoree.dll,
* or CorExitProcess returned (should never happen).
* Just call ExitProcess.
*/
ExitProcess(status);
}
这是代码:
#include <iostream>
#include <WinSock2.h>
#include <IPHlpApi.h>
#include <Ws2tcpip.h>
using namespace std;
#pragma comment(lib, "iphlpapi.lib")
#pragma comment(lib, "ws2_32.lib")
#define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x))
#define FREE(x) HeapFree(GetProcessHeap(), 0, (x))
int __cdecl main()
{
PMIB_TCPTABLE_OWNER_PID pTcpTable;
DWORD tcpTableSize = 0;
char szLocalAddr[128];
struct in_addr IpAddr;
pTcpTable = (PMIB_TCPTABLE_OWNER_PID)MALLOC(sizeof(MIB_TCPTABLE_OWNER_PID));
if(pTcpTable == NULL)
return 1;
tcpTableSize = sizeof(MIB_TCPTABLE_OWNER_PID);
if(GetExtendedTcpTable(pTcpTable, &tcpTableSize, FALSE, AF_INET, TCP_TABLE_OWNER_PID_CONNECTIONS, 0) == ERROR_INSUFFICIENT_BUFFER)
{
FREE(pTcpTable);
pTcpTable = (PMIB_TCPTABLE_OWNER_PID)MALLOC(sizeof(tcpTableSize));
if(pTcpTable == NULL)
return 1;
}
if(GetExtendedTcpTable(pTcpTable, &tcpTableSize, FALSE, AF_INET, TCP_TABLE_OWNER_PID_CONNECTIONS, 0) == NO_ERROR)
{
for(DWORD i = 0; i < pTcpTable->dwNumEntries; i++)
{
IpAddr.S_un.S_addr = (u_long)pTcpTable->table[i].dwRemoteAddr;
InetNtop(AF_INET, &IpAddr, szLocalAddr, 128);
}
}
if(pTcpTable != NULL)
FREE(pTcpTable);
return 0;
}
我不知道这里有什么问题,它只是简单的内存分配和释放,请在这里帮助我!
我很确定你不想要这个:
pTcpTable = (PMIB_TCPTABLE_OWNER_PID)MALLOC(sizeof(tcpTableSize));
,而是
pTcpTable = (PMIB_TCPTABLE_OWNER_PID)MALLOC(tcpTableSize);
// ^^^^^ sizeof removed.
它几乎肯定会崩溃,因为您覆盖了操作系统在退出时清理堆所必需的其他内容,这就是为什么您访问地址9
时会崩溃的原因。
问题就在这里
pTcpTable = (PMIB_TCPTABLE_OWNER_PID)MALLOC(**sizeof**(tcpTableSize));
您需要分配tcpTableSize字节,而不是sizeof(DWORD)