immutable string literal?
    Steven Schveighoffer 
    schveiguy at yahoo.com
       
    Mon Feb 22 05:40:44 PST 2010
    
    
  
On Mon, 22 Feb 2010 08:32:20 -0500, strtr <strtr at spam.com> wrote:
> Daniel Keep Wrote:
>
>>
>> strtr wrote:
>> > On winXP (D1) I can compile/run this code without a problem.
>> > Not even a warning.
>> >
>> > void main() {
>> >   char[] s= "immutable literal?";
>> >   s[$-1] = '!';
>> >   writefln(s);
>> > }
>> > Codepad runs into a segmentation fault.
>> > http://codepad.org/NQfsRoR5
>> >
>> > Why doesn't it result in a compiler error or warning?
>> > If it did I would have noticed this quirk earlier.
>>
>> There's no compiler error because D1 doesn't have a const/immutable  
>> system.
>>
>> There's no crash because Windows doesn't write-protect the data segment
>> which contains the literal.
>
> But according to the specs, it does constitute an error and I suspect  
> string literals are placed in a specific memory location.
> Wouldn't it be possible to error on such code?
Yes, it is possible -- use D2 which has such errors :)  Without a const  
system, D1 cannot distinguish between char[] that originated from a  
literal (i.e. in the static data segment) or which originated from the  
heap.  At the point where you see the line:
s[$-1] = '!';
You don't have the entire history of where s came from.  It can be even  
harder to detect than you think.  For instance, should you allow the  
following code to compile?
int main(char[][] args)
{
    char[] s;
    if(args[1] == "y")
       s = "immutable literal?";
    else
       s = "mutable literal?".dup;
    s[$-1] = "!";
    return 0;
}
This program runs fine unless you pass the exact argument 'y' to the  
program, and then it crashes.  How does the compiler know at the line  
where s is modified that it could have possibly come from a literal?
If you still think it's possible, what about this?
void exclaim(char[] s)
{
    s[$-1] = '!';
}
If this is in its own module, how can the compiler tell whether s is  
immutable or not?
-Steve
    
    
More information about the Digitalmars-d-learn
mailing list