1

My answer here received a comment, regarding the memory allocation in my code. I've used new[] and delete[], because I've read before, that you should never malloc()/free() in C++ (i.e. here). The code in question is essentially:

ULONG outBufLen = sizeof(IP_ADAPTER_ADDRESSES);
GetAdaptersAddresses(0, 0, NULL, NULL, &outBufLen);
PIP_ADAPTER_ADDRESSES pCurrAddresses = (IP_ADAPTER_ADDRESSES *)new uint8_t[outBufLen];
//...
delete[] pCurrAddresses;

The byte-size of memory, which I want to allocate comes from the function GetAdaptersAddresses(). My question is: is there anything wrong with this piece of code? If yes, what would be the proper way in modern C++ to allocate the memory there?

  • malloc()/free() should be out of question - it's C++ code and I don't see any improvement in using malloc() instead of new[] here. Right?

  • std::vector<> seems not right to me - I could write std::vector<uint8_t> bytes(outBufLen, 0); PIP_ADAPTER_ADDRESSES pCurrAddresses = (IP_ADAPTER_ADDRESSES *)bytes.data(); but I would have a bad feeling, because std::vector<>::data() is const).

  • Using std::unique_ptr<uint8_t[]> seems also odd - because I have to cast it into a raw pointer anyway.

Any alternatives?

Community
  • 1
  • 1
Constantin
  • 8,721
  • 13
  • 75
  • 126
  • 1
    `std::vector::data()` returns `const T*` only if called on a `const` vector. Otherwise the non-`const` overload is called, which returns `T*`. – T.C. Jul 09 '14 at 08:56

1 Answers1

2

Your second proposal with std::vector is the right one in C++ in most cases. The data() is not const (well, it is for const vectors, but in your case it is not). C++ standard ensures that data() returns the pointer to contiguous storage of memory for your PODs.

Wojtek Surowka
  • 20,535
  • 4
  • 44
  • 51