内存分配/释放错误(极小代码)

时间:2013-04-11 16:28:20

标签: c++ c winapi memory-management malloc

在运行最后列出的代码时,我会在最后一行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;
}

我无法弄清楚这里的错误,简单的内存分配和释放,请帮助我在这里!

2 个答案:

答案 0 :(得分:4)

我很确定你不想要这个:

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

但是

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

它几乎肯定会崩溃,因为你覆盖了操作系统在退出时清理堆所需的其他东西,这就是你访问地址9时崩溃的原因。

答案 1 :(得分:0)

问题出在这里

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

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