Re: Null terminated strings: bad or good?
- From: Keith Thompson <kst-u@xxxxxxx>
- Date: Sat, 10 Jan 2009 10:09:41 -0800
Harald van Dijk <truedfx@xxxxxxxxx> writes:
On Sat, 10 Jan 2009 01:46:45 -0800, just.a.garbageman wrote:
The standard allows implementations to store the length of the string
somewhere (like, say at string_ptr - sizeof (size_t)). To be more
precise, it does not disallow it. (nor it mentions it)
The standard allows this for string literals, but it would have little
benefit as functions cannot make use of it reliably. The standard
guarantees that strlen("Hello") is 5, but equally that
strlen("Hello" + 1) is 4. 4 cannot be stored in the bytes before "ello".
And consider this:
char str[] = "Hello";
str[3] = rand() % CHAR_MAX;
strlen(str) is now either 5 or 3, depending on whether the value you
stored happened to be 0.
Even more fun:
char str[] = "Hello"; /* perhaps this is at file scope */
/* ... */
char *ptr = some_arbitrary_pointer_value();
*ptr = some_arbitrary_char_value();
Did strlen(str) change? If so, to what? The compiler might be able
to prove that it didn't change in some cases, but in general you can't
tell without re-scanning the array.
Ok, suppose you recompute the stored strlen() every time the array
might have changed.
char str[] = "Hello";
str[5] = '.';
Now str doesn't even contain a string (which is perfectly legitimate
as long as you don't try to treat it as one). What value do you store
in the hidden strlen()? And how much time will your program spend
re-scanning arrays rather than doing actual work?
--
Keith Thompson (The_Other_Keith) kst-u@xxxxxxx <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
.
- Follow-Ups:
- Re: Null terminated strings: bad or good?
- From: Han from China - Master Troll
- Re: Null terminated strings: bad or good?
- References:
- Re: Null terminated strings: bad or good?
- From: Ben Bacarisse
- Re: Null terminated strings: bad or good?
- From: Han from China - Master Troll
- Re: Null terminated strings: bad or good?
- From: just . a . garbageman
- Re: Null terminated strings: bad or good?
- From: Harald van Dijk
- Re: Null terminated strings: bad or good?
- Prev by Date: Re: What is C header file sys/cdefs.h used for?
- Next by Date: Re: Memory layout in unions
- Previous by thread: Re: Null terminated strings: bad or good?
- Next by thread: Re: Null terminated strings: bad or good?
- Index(es):
Relevant Pages
|