To dup or not to dup?

Frits van Bommel fvbommel at REMwOVExCAPSs.nl
Sun Feb 25 13:15:46 PST 2007


Jürgen Herz wrote:
> Hi,
> 
> I'm absolutely new to D and about to see if D is a language I could like.
> On http://www.digitalmars.com/d/cppstrings.html I found
> 
> char[] s1 = "hello world";
> char[] s2 = "goodbye      ".dup;
> s2[8..13] = s1[6..11];		// s2 is "goodbye world"
> 
> The .dup is needed because string literals are read-only in D, the .dup
> will create a copy that is writable.
> 
> 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).

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.

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).



More information about the Digitalmars-d mailing list