我正在关注管理 IP 地址的 C++ msdn 参考。示例中的内存分配使用 malloc 而不是 new。我的理解是 malloc 永远不应该在 C++ 中使用。我将如何将这些 malloc 转换为 new ?
链接:MSDN 参考
有问题的代码:
MIB_IPADDRTABLE *pIPAddrTable;
DWORD dwSize = 0;
DWORD dwRetVal;
pIPAddrTable = (MIB_IPADDRTABLE*) malloc( sizeof(MIB_IPADDRTABLE) );
if (GetIpAddrTable(pIPAddrTable, &dwSize, 0) == ERROR_INSUFFICIENT_BUFFER)
{
free( pIPAddrTable );
pIPAddrTable = (MIB_IPADDRTABLE *) malloc ( dwSize );
}
if ( (dwRetVal = GetIpAddrTable( pIPAddrTable, &dwSize, 0 )) != NO_ERROR )
{
printf("GetIpAddrTable call failed with %d\n", dwRetVal);
}
printf("IP Address: %ld\n", pIPAddrTable->table[0].dwAddr);
printf("IP Mask: %ld\n", pIPAddrTable->table[0].dwMask);
printf("IF Index: %ld\n", pIPAddrTable->table[0].dwIndex);
printf("Broadcast Addr: %ld\n", pIPAddrTable->table[0].dwBCastAddr);
printf("Re-assembly size: %ld\n", pIPAddrTable->table[0].dwReasmSize);
if (pIPAddrTable)
free(pIPAddrTable);