2

在运行最后列出的代码时,我在最后一行得到了一个休息,FREE(pTcpTable);如果我继续这个错误就会出现:

“netMon.exe 中 0x7737096E (ntdll.dll) 处的未处理异常:0xC0000005:访问冲突读取位置 0x00000009。”

crt0dat.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;
}

我无法弄清楚这里出了什么问题,它的内存分配和释放很简单,请在这里帮助我!

4

2 回答 2

4

我很确定你不想要这个:

    pTcpTable = (PMIB_TCPTABLE_OWNER_PID)MALLOC(sizeof(tcpTableSize));

但反而

    pTcpTable = (PMIB_TCPTABLE_OWNER_PID)MALLOC(tcpTableSize);
    //                                          ^^^^^ sizeof removed.

它几乎肯定会崩溃,因为您覆盖了操作系统在退出时清理堆所必需的其他内容,这就是您遇到访问地址崩溃的原因9

于 2013-04-11T16:35:07.330 回答
0

问题就在这里

pTcpTable = (PMIB_TCPTABLE_OWNER_PID)MALLOC(**sizeof**(tcpTableSize));

您需要分配 tcpTableSize 字节,而不是 sizeof(DWORD)

于 2013-04-11T16:43:04.980 回答