Why are string literals zero-terminated?

Lars T. Kyllingstad public at kyllingen.NOSPAMnet
Tue Jul 20 06:38:33 PDT 2010


On Tue, 20 Jul 2010 13:26:56 +0000, Lars T. Kyllingstad wrote:

> On Tue, 20 Jul 2010 14:59:18 +0200, awishformore wrote:
> 
>> Following this discussion on announce, I was wondering why string
>> literals are zero-terminated. Or to re-formulate, why only string
>> literals are zero-terminated. Why that inconsistency? What's the
>> rationale behind it? Does anyone know?
> 
> So you can pass them to C functions.

Note that even though string literals are zero terminated, the actual 
string (the array, that is) doesn't contain the zero character.  It's 
located at the memory position immediately following the string.

  string s = "hello";
  assert (s[$-1] != '\0');  // Last character of s is 'o', not '\0'
  assert (s.ptr[s.length] == '\0');

Why is it only so for literals?  That is because the compiler can only 
guarantee the zero-termination of string literals.  The memory following 
a string in general could contain anything.

  string s = getStringFromSomewhere();
  // I have no idea where s is coming from, so I don't
  // know whether it is zero-terminated or not.  Better
  // make sure.
  someCFunction(toStringz(s));

-Lars


More information about the Digitalmars-d-learn mailing list