dynamic arrays and the lack of them in C

I love Pascal and Delphi. In particular I love its memory management.
I can use string, array of byte types. They are both dynamic arrays. They are not just pointers to a memory region, they have a size or Length (how Delphi calls them).
The great thing about them is that they can be re-sized. But an other great thing is that you can check their sizes no matter what (if you forgot to remember them, or if you receive them as argument of a function/procedure/method).
SetLength()
Length()
Low()
High()
Open array parameters
^^^^ This is what I need in C!

In C it’s like they want to hide this information from you. First, there is no such thing as dynamic array in C (there are only pointers). There are arrays in C++ (but I read that you should avoid them at all cost, and use vector instead), but also you cannot re-size them, so they are not fixed length, but not really dynamic either.
So how can you get the length of an array or memory region?
common methods:
In C you can use #define lengthof(array) (sizeof(array)/sizeof(array[0])) if it’s a fixed length array, but you cannot use it on function arguments, or pointers…

There is a clever template (if you write it) in C++
template
inline unsigned int length( T(&a)[N] ) { return N; }
that can be used to determine length of arrays.

So where are the real dynamic, realizable arrays, and how to implement them?
If you want to allocate memory run-time (and re-size them) you can use malloc() (realloc() and free())
That’s all fine until you want to get the size of them. Which can happen if you allocate the memory outside of a function where you want to use it. There is no std libc function to get the (malloc) allocated memory size which is kept somewhere (so free() can free it, realloc can re-size it and available memory regions can be kept track of). There is however a GNU extension malloc_usable_size() which I, we desperately need (even if we didn’t know it).
.. Well we need an array whose size we can check no matter if it’s dynamic or static, but…
Also note that malloc_usable_size does NOT actually return the requested size, but the allocated one (due to alignment, minimum block size), but at least we can use it for asserts.
So we still need to keep track of array sizes separately (extra variables, extra arguments) and risk messing them up…
(or rewrite everything to use structures of size, pointer pairs)

Another topic is multidimensional (dynamic) arrays (not just arrays of arrays)…

Note: This actually I have written just now 🙂 See I do not just reuse ages old materials:)

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.