Search code examples
arraysd

Error: range violation in D programming


I have dynamic array in struct and a method that uses the dynamic array. The problem is that I get range violation error when I run the program. However when I create a new dynamic array inside the method, it works fine. The following code causes problem.

struct MyStr {
 int[] frontArr;

    this(int max = 10) {
         frontArr = new int[10];
    }

    void push(int x) {
         frontArr[0] = x;
    }
}

void main() {
    MyStr s;
    s.push(5);
}

However, this one works;

struct MyStr {
 int[] frontArr;

    this(int max = 10) {
         frontArr = new int[10];
    }

    void push(int x) {
         frontArr = new int[10]; // <---Add this line
         frontArr[0] = x;
    }
}

void main() {
    MyStr s;
    s.push(5);
}

I basically add that line to test the scope. It seems like the initialized FrontArr can't be seen in push(int x) method. Any explanation?

Thanks in advance.


Solution

  • Initialization of structs must be guaranteed. This is you do not want the default construction of a struct to throw an exception. For this reason D does not support default constructors in structs. Imagine if

    MyStr s;
    

    resulted in an exception being thrown. Instead D provides its own default constructor which initializes all fields to the init property. In your case you are not calling your constructor and just using the provided defaults which means frontArr is never initialized. You want something like:

    void main() {
        MyStr s = MyStr(10);
        s.push(5);
    }
    

    It should probably be a compiler error to have default values for all parameters of a struct constructor. Bugzilla