To dup or not to dup?
Jürgen Herz
juergen at jherz.redirectme.net
Mon Feb 26 02:46:44 PST 2007
Frits van Bommel wrote:
> Jürgen Herz wrote:
>> The same with
>> char []a = "Txst";
>> a[1] = 'a';
>>
>> I find that interesting because here it also works (compiles and runs)
>> without .dup (DMD 1.007). Has the language changed since writing that
>> web page?
>
> Let me guess, you're running Windows. (checks post header) Yep.
> Segfaults for me (running Linux).
That's right.
I've now also set up dmd on Linux and it segfaults here too.
> This isn't enforced on Windows. I'm not sure whose fault that is, but I
> assume Microsoft :P.
> Before you think I'm a MS basher, I'd like to mention that IIRC it's not
> enforced for C either on Windows: if you initialize char* with a string
> literal and try to modify it -- which is illegal in C for the very same
> reason -- it won't complain.
It also isn't enforced for C on Linux (gcc) though it also doesn't
crash. Anyways, that's C and D (resp. dmd) could do better.
> Just because it doesn't crash on your computer doesn't mean it's legal
> or that it'll work on every computer (or even on your computer with a
> different compiler, for that matter -- though in this case it probably
> will if it's because of Windows).
I understand that it is and why it is illegal. And crashing on Linux I'm
relieved seeing the "right" consequence of doing illegal things.
But I'm not convinced of the compiler. In my point of view a language
and a compiler should catch as many programming errors at the earliest
point possible, that is at compile time.
What I started with was to find out if there's a const in D. Well, it is
but ...
To me it looks very inconsequent:
char []a = "Test";
a[1] = 'x';
segfaults while
const char []a = "Test";
a[1] = 'x';
is caught at compile time with "Error: string literals are immutable".
Interestingly
const char []a = "Test";
a[1..2] = "x";
compiles without warnings though still segfaults.
Even worse:
const char []a = "Test";
test(a);
void test(char []s)
{
s[1] = 'x';
}
Not only there doesn't seem no way to declare a function argument const,
a non-const argument removes const without warnings - and promptly
segfaults in test.
On windows the result of that code is very interesting. Since it doesn't
segfault, one can printf a and s after manipulation. And it's "Txst" in
test() and "Test" outside.
BTW
const char []a = "Test".dup;
gives
consttest.d(3): Error: cannot evaluate
_adDupT(&_D12TypeInfo_G4a6__initZ,"Test") at compile time.
What does in want to tell me?
Jürgen
More information about the Digitalmars-d
mailing list