3 ms·
That's a lot of words just to be pedantic. What a heap allocator does in its bookkeeping is not necessarily "storing the length of the array" - and whatever it
by benched 13y ago
That's a lot of words just to be pedantic. What a heap allocator does in its bookkeeping is not necessarily "storing the length of the array" - and whatever it does isn't sensibly available to the running program. Yes, the size of a static array is known at compile time, but it's length is still not available to the running program unless the programmer explicitly arranges for it to be.
- rayiner 13y agoIf you're programming in C, it's not unreasonable to be pedantic about stuff like this. :D
- jevinskie 13y agoI looked into this. It seems that OS X provides malloc_size. [0] I wonder if other *BSDs have it or if it is a XNUism. I can't find an equivalent for glibc, which I find disappointing given how immense glibc is. Even if it is potentially a "shoot yourself in the foot" feature, I can see many judicious uses of it. And even with such a size query, it is still obviously not something nice and built into the language. But C folks are used to that! =P [0]: https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man3/malloc_size.3.html https://developer.apple.com/library/mac/documentation/Darwin...
- benched 13y agoThen I retract my "not sensibly available" for "maybe sensibly available on your platform". But, it is still not the array size.
- deleted 13y ago[deleted]
- sitharus 13y agomalloc_size won't give you the size of the array though, it'll give you the number of bytes malloced. malloc is free to return any number of bytes, so long as it's at least the size requested.
- RogerL 13y agoYes, and consider char* c = malloc(...); char* d = c+ 100; malloc_size(d); Perfectly cromulent C, and I submit the result of the call is not what you might hope it will be. The article is correct. There is no way in the C language to get the size of the array. Any implementation is, of course, free to build in anything extra in the memory allocator, but it is not part of the language. Specifically, you cannot add anything to the array itself, because memory layout is prescribed. ptr[0] must point to the first byte of memory that was allocated, and if you added some kind of table you'd be pointing to that.