-1

I am using C++ new/delete operators to allocate/deallocate the buffers. I think for each allocated buffer, there should be an additional info block stores the size and other info about the buffer. How to know more details about this info block? I need to override these two operators and find such an info block is useful to my implementation.

Thanks

alancc
  • 487
  • 2
  • 24
  • 68

2 Answers2

1

First off, you cannot know this information. When you use dynamic arrays in C++, it is your responsibility to track the allocated size separately. This is one of the main reasons nobody should be using dynamic arrays, ever, and just use std::vector instead, which tracks the size for you so you can't lose it or confuse it with someone else's size or forget to update it.

Now the question of whether the size is stored somewhere internally. That depends. If you just get memory from malloc and pass it to free, you don't need to know the allocated size, since the memory allocator already tracks this information internally, invisibly to you. The only reason that C++ would need to know the number of array elements is in order to call all the right destructors. Therefore, the size information is only strictly necessary if the array element objects are not trivially destructible.

At least the Itanium ABI for C++ does not store any extra size information unless the objects are not trivially destructible. Other ABIs may differ. But whichever way you turn it, there's no way for you to know.

In summary: use std::vector.

(Note that std::vector doesn't have a hidden cost, since it doesn't internally contain a native dynamic array, but rather it manages all the elements directly. Just like dynamic arrays it needs to track the number of elements, but unlike dynamic arrays, it makes this number publicly visible to the user. To me this is one more indication that dynamic arrays are much better solved in library than in the core language.)

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
0

What information are you looking for about the buffer? If you had something like this:

int* ptr = new int[size];

you know the size of your buffer and the type of variables that your buffer stores.

If you want your buffer to grow or shrink, use a vector as said in the other response.

zachyee
  • 348
  • 1
  • 8