When inside a constructor a multidimensional array is declared whose size
depends on a variable, e.g.  int n = 5; int a[n][n];, address calculation for
accessing the array elements is wrong. Example code:


--- snip ---
int result;

class A {
        public:
        A();
};

void remember(int i) {
        result = i;
}

void test() {
        int n = 5;
        int a[n][n];

        a[0][4] = 42;
        a[4][0] = 43;

        remember(a[0][4]);  // a[0][4] still is 42
}

A::A() {
        int n = 5;
        int a[n][n];

        a[0][4] = 42;
        a[4][0] = 43;  // overwrites a[0][4]!

        remember(a[0][4]);  // a[0][4] is 43
}

int main(int argc, char** argv) {
        A* object = new A();
        return result;
}

--- snip ---

In the above code, the constructor will set result to 43. The identical code of
test() will set result to 42.

The assembler code of test() and the constructor differs slightly: in test(), n
is stored in %ecx, moved to %eax for some computation, and is later moved to
%eax a second time. In the constructor, however, n is moved to %eax directly and
later, where test() would movl %ecx, %eax, the constructor does movl 0, %eax
instead.

$gcc --version
gcc (GCC) 3.3.5 (Debian 1:3.3.5-5)

-- 
           Summary: Dynamically sized static multidimensional array access
                    in constructor uses wrong address
           Product: gcc
           Version: 3.3.5
            Status: UNCONFIRMED
          Severity: normal
          Priority: P2
         Component: c++
        AssignedTo: unassigned at gcc dot gnu dot org
        ReportedBy: lathander at gmx dot de
                CC: gcc-bugs at gcc dot gnu dot org
 GCC build triplet: i486-linux ?
  GCC host triplet: i486-linux ?
GCC target triplet: i486-linux ?


http://gcc.gnu.org/bugzilla/show_bug.cgi?id=19254

Reply via email to