[Issue 523] New: I think this is a GC bug

Jarrett Billingsley kb3ctd2 at yahoo.com
Wed Nov 15 12:52:27 PST 2006


<d-bugmail at puremagic.com> wrote in message 
news:bug-523-3 at http.d.puremagic.com/issues/...

> I think that this is a bug in gc/compiler
>
> char [] foo() {
>  char [10] arr = "hello, wor";
>  return arr[0..4]; // or return arr;
> }
>
> void main() {
>  printf(foo());
> }
>
> doesn`t work - it prints some rubbish, so, as i guess, arr is collected
> when function 'foo' returns. if I use char [] instead of char[10] all 
> works
> fine.

You'll get the same thing in C or C++, because in D, as in those languages, 
statically-sized arrays are on the stack.  When you return the slice of that 
data, you're hiding from the compiler the fact that you're returning a 
pointer to a stack variable.  You can fix this by using "return arr[0 .. 
4].dup;", as that'll copy the data from the stack onto the heap.

When you use dynamic arrays, though, they're always allocated on the heap, 
so it works fine. 





More information about the Digitalmars-d-bugs mailing list