[Issue 2418] Same-value string (char[]) literals get overwritten (unlike array literals)
d-bugmail at puremagic.com
d-bugmail at puremagic.com
Tue Oct 14 22:02:40 PDT 2008
http://d.puremagic.com/issues/show_bug.cgi?id=2418
2korden at gmail.com changed:
What |Removed |Added
----------------------------------------------------------------------------
Status|REOPENED |RESOLVED
Resolution| |INVALID
------- Comment #4 from 2korden at gmail.com 2008-10-15 00:02 -------
> ------- Comment #3 from business3 at twistedpairgaming.com 2008-10-14
>
> I don't think that's applicable (or at least, it shouldn't be). Here's a
> shortened example:
>
> char[] a = "AAA";
> a[0] = '!';
> char[] b = "AAA";
>
> It's absurd that 'b' should become "!AA".
Well, that's what I expect, at least :)
> It's clear that the compiler is
> "optimizing" both "AAA" string literals into the same reference:
>
> char[] _tmp1 = "AAA";
> char[] a = _tmp1;
> a[0] = '!';
> char[] b = _tmp1;
Of course it does! This string literal is put into executable. "AAA" is just a
pointer to it.
Please, understand that char[] is nothing more than a pointer to a string and
an associated length. When you change the string via pointer, everyone who has
that pointer gets the change. Compare to object:
class A
{
int i = 15;
}
A aaa = new A(); // aaa is an analog of "AAA"
A a = aaa;
writefln(a); // prints 15
a.i = 42;
A b = aaa;
writefln(b); // why the hell it prints 42????
This is because you don't make a copy of aaa.
Here is another example:
while (true) {
char[] a = "AAA";
a[0] = '!'; // in the next iteration, should a be "AAA" again?
}
If answer is yes, then there should be a memory allocation in line 2 under the
hood. You can't get new string every time without a memory allocation. This,
however, definitely should not occur. If you want to make an allocation - do it
yourself explicitely.
Code with the behaviour you expect should be as follows:
while (true) {
char[] a = "AAA".dup;
writefln(a);
a[0] = '!';
writefln(a);
}
This is by design, it works as it should. It can't be 'fixed' because it is not
broken.
> Besides, at the very least there's still an inconsistency:
>
> char[] a = "AAA";
> a[0] = '!';
> char[] b = "AAA"; // b is "!AA"
>
> char[] c = ['A', 'A', 'A'];
> c[0] = '!';
> char[] d = ['A', 'A', 'A']; // d is "AAA"
I agree, this might be a bug, d really ought to be "!AAA"!
Do you want to create a new bugreport so that the latter case would be 'fixed'?
:)
--
More information about the Digitalmars-d-bugs
mailing list