A bit smarter is to combine the length field with the metadata stored already by malloc.  Malloc (generally) knows the size of the allocation, probably not the exact size, but the size rounded up to 8 or 16 bytes.  For example with glibc you call malloc_usable_size(ptr) (a non-standard function of course).<p>You can encode the byte length of the string minus the rounded up size (known by malloc) using the same trick that OCaml uses: <a href="https:&#x2F;&#x2F;rwmj.wordpress.com&#x2F;2009&#x2F;08&#x2F;05&#x2F;ocaml-internals-part-2-strings-and-other-types&#x2F;" rel="nofollow">https:&#x2F;&#x2F;rwmj.wordpress.com&#x2F;2009&#x2F;08&#x2F;05&#x2F;ocaml-internals-part-2...</a>  Using this trick you can get the byte length of the string from the base pointer in O(1).  Such strings can also contain \0 characters.<p>Thus you don&#x27;t need to store the string length explicitly as a separate field, and you can even make string pointers within the string work, and it&#x27;s backwards compatible with legacy functions that expect a null-terminated string (albeit it won&#x27;t work if you pass a string containing \0 to one of those legacy functions, but that is to be expected).