问题描述
谁能解释为什么这段代码在第一次调用 GetIpAddrTable 时会抛出异常?运行时库抱怨堆损坏。 重启后的第一次调用有效,但之后就不行了。
#define MALLOC(x) HeapAlloc(GetProcessHeap(),(x))
#define FREE(x) HeapFree(GetProcessHeap(),(x))
BOOL GetMyIPAddress(LPVOID addressBuffer) {
int i;
BOOL result = FALSE;
IN_ADDR loopbacksubnet = { 0 },loopbackNetwork = { 0 };
IN6_ADDR ipv6Loopback;
ZeroMemory(&ipv6Loopback,sizeof(IN6_ADDR));
inet_pton(AF_INET,"255.255.0.0",&loopbacksubnet);
inet_pton(AF_INET,"127.0.0.1",&loopbackNetwork);
inet_pton(AF_INET6,"::1",&ipv6Loopback);
/* Variables used by GetIpAddrTable */
PMIB_IPADDRTABLE pIPAddrTable = (MIB_IPADDRTABLE*)MALLOC(sizeof(MIB_IPADDRTABLE));
if (pIPAddrTable)
{
DWORD dwSize = 0;
ZeroMemory(pIPAddrTable,dwSize);
DWORD dwRetVal = 0;
IN_ADDR IPAddr = { 0 };
/* Variables used to return error message */
LPVOID lpMsgBuf = NULL;
// Make an initial call to GetIpAddrTable to get the
// necessary size into the dwSize variable
if (GetIpAddrTable(pIPAddrTable,&dwSize,FALSE) == ERROR_INSUFFICIENT_BUFFER) {
FREE(pIPAddrTable);
pIPAddrTable = (MIB_IPADDRTABLE*)MALLOC(dwSize);
if (pIPAddrTable == NULL) {
printf("Memory allocation Failed for GetIpAddrTable\n");
return FALSE;
}
else {
ZeroMemory(pIPAddrTable,dwSize);
// Make a second call to GetIpAddrTable to get the
// actual data we want
dwRetVal = GetIpAddrTable(pIPAddrTable,FALSE);
if (dwRetVal != NO_ERROR) {
printf("GetIpAddrTable Failed with error %d\n",dwRetVal);
if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYstem | FORMAT_MESSAGE_IGnorE_INSERTS,NULL,dwRetVal,MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT),// Default language
(LPTSTR)&lpMsgBuf,NULL)) {
_RPT1(_CRT_WARN,"\tError: %s",lpMsgBuf);
LocalFree(lpMsgBuf);
return FALSE;
}
}
for (i = 0; i < (int)pIPAddrTable->dwNumEntries; i++) {
IPAddr.S_un.S_addr = (u_long)pIPAddrTable->table[i].dwAddr;
if (((IPAddr.S_un.S_addr & loopbacksubnet.S_un.S_addr) ^ (loopbackNetwork.S_un.S_addr & loopbacksubnet.S_un.S_addr)) != 0)
{
((IN_ADDR*)addressBuffer)->S_un.S_addr = IPAddr.S_un.S_addr;
result = TRUE;
break;
}
}
FREE(pIPAddrTable);
pIPAddrTable = NULL;
}
}
}
return result;
}
它是从这里解除的: https://docs.microsoft.com/en-us/windows/win32/api/iphlpapi/nf-iphlpapi-getipaddrtable
解决方法
谢谢大家 - 我想我已经解决了这个问题。是其他地方的问题 - 我讨厌调试服务!