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

godio 发布于 2019-03-09 c 最后更新 2019-03-09 14:38 3 浏览

在运行最后列出的代码时,我在最后一行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;
}
我无法弄清楚这里有什么问题,简单的内存分配和释放,请在这里帮助我!
已邀请:

fet

赞同来自:

我很确定你不想要这个:

    pTcpTable = (PMIB_TCPTABLE_OWNER_PID)MALLOC(sizeof(tcpTableSize));
但反而
    pTcpTable = (PMIB_TCPTABLE_OWNER_PID)MALLOC(tcpTableSize);
    //                                          ^^^^^ sizeof removed.
它几乎肯定会崩溃,因为你覆盖了操作系统在退出时清理堆所需的其他东西,这就是你得到访问地址9的崩溃的原因。

lqui

赞同来自:

问题出在这里

pTcpTable = (PMIB_TCPTABLE_OWNER_PID)MALLOC(**sizeof**(tcpTableSize));
你需要分配tcpTableSize字节,而不是sizeof(DWORD)