www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Pointer to string allows assigning int[]?

reply "cal" <callumenator gmail.com> writes:
Is the following a bug?

import std.c.string, core.memory;

void* makeNew(T)()
{
     T t = T.init;
     void* ptr = GC.malloc(T.sizeof);
     memcpy(ptr, &t, T.sizeof);
     return ptr;
}

void main()
{
     alias string T;
     T* iptr = cast(T*)makeNew!(T);
     (*iptr) = [1,2,3]; // this is allowed
}
Nov 12 2012
next sibling parent "simendsjo" <simendsjo gmail.com> writes:
On Monday, 12 November 2012 at 21:03:51 UTC, cal wrote:
 Is the following a bug?

 import std.c.string, core.memory;

 void* makeNew(T)()
 {
     T t = T.init;
     void* ptr = GC.malloc(T.sizeof);
     memcpy(ptr, &t, T.sizeof);
     return ptr;
 }

 void main()
 {
     alias string T;
     T* iptr = cast(T*)makeNew!(T);
     (*iptr) = [1,2,3]; // this is allowed
 }

It's not a bug. string is an alias for immutable(char)[]. ubyte can be implicitly converted to char. All your numbers are less than 256, so dmd is able to convert them to char. If you try this, it fails. string s = [256]; // 256 is > char.max
Nov 12 2012
prev sibling next sibling parent "cal" <callumenator gmail.com> writes:
On Monday, 12 November 2012 at 21:08:43 UTC, simendsjo wrote:
 It's not a bug.

 string is an alias for immutable(char)[].
 ubyte can be implicitly converted to char.
 All your numbers are less than 256, so dmd is able to convert 
 them to char.
 If you try this, it fails.
 string s = [256]; // 256 is > char.max

Ah right of course, thank you.
Nov 12 2012
prev sibling next sibling parent Andrej Mitrovic <andrej.mitrovich gmail.com> writes:
On 11/12/12, cal <callumenator gmail.com> wrote:
 Is the following a bug?

Reduced: void main() { string x = "foo"; string* y = &x; *y = [1, 2, 3]; assert(x == "foo"); // fails } Yes this is a bug, especially since the string is typed as immutable(char)[].
Nov 12 2012
prev sibling next sibling parent Andrej Mitrovic <andrej.mitrovich gmail.com> writes:
On 11/12/12, simendsjo <simendsjo gmail.com> wrote:
 It's not a bug.

It's a bug, he's overwriting immutable data.
Nov 12 2012
prev sibling next sibling parent Andrej Mitrovic <andrej.mitrovich gmail.com> writes:
On 11/12/12, Andrej Mitrovic <andrej.mitrovich gmail.com> wrote:
 On 11/12/12, simendsjo <simendsjo gmail.com> wrote:
 It's not a bug.

It's a bug, he's overwriting immutable data.

Ahh sorry I completely misread the code. There's no bug here actually.
Nov 12 2012
prev sibling parent Andrej Mitrovic <andrej.mitrovich gmail.com> writes:
On 11/12/12, Andrej Mitrovic <andrej.mitrovich gmail.com> wrote:
 Yes this is a bug, especially since the string is typed as
 immutable(char)[].

My bad, the string contents aren't being modified. Not a bug.
Nov 12 2012