0

I would use the GetAdaptersAddresses() function of windows to get some informations about the adapters of the computer. In this MSDN page there is a big example of how to use it. But I'm using C++ so I would stick with the new keyword and not malloc (C native). How can I rewrite the parts that uses malloc with new?

EDIT 1

std::vector<PIP_ADAPTER_ADDRESSES> buffer;
ULONG outBufferLen = 0;

if (GetAdaptersAddresses(AF_INET, GAA_FLAG_INCLUDE_PREFIX, NULL, NULL, &outBufferLen) == ERROR_BUFFER_OVERFLOW)
{
    buffer.resize(outBufferLen);

    PIP_ADAPTER_ADDRESSES addresses = reinterpret_cast<PIP_ADAPTER_ADDRESSES>(buffer.data());

    if (GetAdaptersAddresses(AF_INET, GAA_FLAG_INCLUDE_PREFIX, NULL, addresses, &outBufferLen) == NO_ERROR)
    {
        for (; addresses != NULL; addresses = addresses->Next)
        {
            ...
        }
    }
}

EDIT 2

ULONG outBufferLen = 0;

if (GetAdaptersAddresses(AF_INET, GAA_FLAG_INCLUDE_PREFIX, NULL, NULL, &outBufferLen) == ERROR_BUFFER_OVERFLOW)
{
    PIP_ADAPTER_ADDRESSES p = new IP_ADAPTER_ADDRESSES[outBufferLen / sizeof(IP_ADAPTER_ADDRESSES)];

    if (GetAdaptersAddresses(AF_INET, GAA_FLAG_INCLUDE_PREFIX, NULL, p, &outBufferLen) == NO_ERROR)
    {
        ....
    }
}
Ajay
  • 18,086
  • 12
  • 59
  • 105
Stefano
  • 3,213
  • 9
  • 60
  • 101
  • The easier solution is to use a `std::vector`, and resize that. – MSalters Nov 25 '11 at 15:06
  • @MSalters could I do something like what I wrote in the EDIT 2? – Stefano Nov 25 '11 at 15:44
  • Well, that rounds down instead of up. Unless `outBufferLen` is a mulitple of `sizeof(IP_ADAPTER_ADDRESSES)`, you've got a buffer overflow. Also, please note that you won't actually get a `IP_ADAPTER_ADDRESSES[]` from `GetAdaptersAddresses`. – MSalters Nov 25 '11 at 16:00
  • @MSalters ok so, could you please make me an example of how should I implement vector to get the code working? – Stefano Nov 25 '11 at 16:15

1 Answers1

1

You can't directly rewrite that code using new/delete, because introducing new would induce risk of exceptions and that code is not exceptions safe. A dumb way would be to call ::operator new( size_t, const nothrow_t&) instead of malloc() - but this is really ugly.

The real solution is to rewrite all code using proper C++ classes. std::vector would be a good fit for pAddresses and you'd need a RAII wrapper for lpMsgBuf.

sharptooth
  • 167,383
  • 100
  • 513
  • 979