Search code examples
d

Escaping reference to local variable


I am new to the D language. While trying to create a simple function that returns a byte array, I run into errors when trying to return my value. Is there a different way I am supposed to return a local variable from a function?

On the the return line, I get error Error: escaping reference to local c

My code:

byte[] xorFixed(byte[] a, byte[] b){
   if (a.sizeof != b.sizeof) return null;
   byte[a.sizeof] c;
   for (int i = 0; i < a.sizeof; i++)
   {
      c[i] = (a[i] ^ b[i]);

   return c;
}

Solution

  • byte[] and byte[some_size] are two different types. A byte[some_size] is a static array that is copied around when used and a byte[] is a slice or dynamic array that points to its values.

    When you try to return c, since the return value is a slice, it tries to take a pointer to c... which is a local value that ceases to exist when the function returned. If this compiled, it would give you gibberish or a crash at runtime!

    You need to fix the type. c should not be byte[a.sizeof]. It should just be a plain byte[]. To set the size of an array, use .length instead of .sizeof.

    if (a.length != b.length) return null; // changed sizeof -> length
    byte[] c; // changed type
    c.length = a.length; // this sets the length of c to match a
    for (int i = 0; i < a.length; i++) // changed sizeof to length
    

    That will do what you want.