0

Possible Duplicate:
Is there any way to determine the size of a C++ array programmatically? And if not, why?

Can I get the length of a dynamically allocated array in C++, if not, how does C++'s delete operator know how many elements to free.

I searched the forum and found that for dynamically allocated arrays, the length are stored in the four bytes before the array's header or somewhere else. How can I get this value?

Community
  • 1
  • 1
cheng
  • 2,106
  • 6
  • 28
  • 36

4 Answers4

2

The four bytes before the header are definitely an implementation detail you shouldn't use. If you need to know the size of your array, use a std::vector.

thiton
  • 35,651
  • 4
  • 70
  • 100
1

In short, you can't. This is implementation defined, so you cannot access it. You can (and have to), however, store it in a variable, or use some types that control the size, such as std::vector, std::string, etc.

The delete[] operator knows because the implementation of the C++ library has that information, but it is not available to the C++ program. In some implementations, that's the case, it is stored in some bytes before the actual address of the pointer, but again, you cannot know it.

Diego Sevilla
  • 28,636
  • 4
  • 59
  • 87
  • Thanks for your answer. If it is so, then how does the compiler know this value to do delete []? If the compiler can access this value, why does the compiler hide this value from users? – cheng Sep 20 '11 at 11:42
  • It is not the compiler, but the library. It is hidden in the code of `delete[]`, the same way you hide, say, the `private` variables in your classes. Summary: you cannot access it. – Diego Sevilla Sep 20 '11 at 11:43
1

You cannot. However, std::vector<T> v(N) is almost exactly the same thing as new T[N] and offers v.size(), so you should really be using that, unless you have a terrific reason why you want to use the manual array.

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

Another option is to define your own allocator (overloading operator new[] and delete[] for whatever class you care about or doing #define malloc mymalloc and #define free myfree depending on your situation). Where you store your array length is up to you but generally one would allocate extra bytes (whatever amount is the proper amount for memory alignment - generally 4, 8, or 16) before the beginning of the array and store the length there.

mheyman
  • 4,211
  • 37
  • 34