Finding Available Length Of Strings...

Martin Weitzel martin at mwtech.UUCP
Sat Nov 24 13:03:34 AEST 1990


In article <1946 at necisa.ho.necisa.oz> boyd at necisa.ho.necisa.oz (Boyd Roberts) writes:
[in a thread dealing with the C representation for character strings]
>
>All these fixed length character strings are a poor man's solution.
>Dynamic structures aren't that hard to code up, and once you have
>the right library routines it's trivial to use them with future code.
>Code them once, use them everywhere.

I can second this. I once tried to enhance C's elegant and space
efficient character string representation with dynamic space
allocation. I ended up in a similar trick as the one often used
in malloc:

Character strings of varying lenght were represented by a pointer
to the first byte and terminated by a '\0'-character - exactly the
way C does this normaly. So, a program could normaly use "char *" variables
for such strings and hand them to all functions with only read-access
in the normal way.
	                                    +----------+
	for "read only" access              |   '\0'   |
	use normaly, for write              | ........ |
	access use special functions        | 3rd char |
	+--------+                          | 2nd char |
	| char * -------------------------> | 1st char |
	+--------+                          +----------+
	    ^                               |  length  |
	    |                               +----------+
	    +--------------------------------- char ** |
	            back-pointer            +----------+

Additionally for such varying strings there were a special setup
operation for the said "char *" variable, which allocated space for
the string itself and additionally, at some adress immediatly *below*
the string space for a length field and a back-pointer to the
variable. After such an initialization, things looked basically as
above.

There were some special functions, that - when changing the string -
looked for the length field, and did eventually realloc the space.
The only thing which had to be done carefully (besides only using
the special functions to change them and not to forget freeing them
when the pointer goes out of scope) was not to set up pointers into
them, as the reallocation could only change the one reference which
it new from the back-pointer. This included that these strings should
never be passed to functions as arguments, and then changed more
than once from within the function ...

(Well, no problem without solution: One could either pass pointers
to them or "swap them out and in" from a local instances.)
-- 
Martin Weitzel, email: martin at mwtech.UUCP, voice: 49-(0)6151-6 56 83



More information about the Comp.lang.c mailing list