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 usingmalloc()
instead ofnew[]
here. Right?std::vector<>
seems not right to me - I could writestd::vector<uint8_t> bytes(outBufLen, 0); PIP_ADAPTER_ADDRESSES pCurrAddresses = (IP_ADAPTER_ADDRESSES *)bytes.data();
but I would have a bad feeling, becausestd::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?