From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: (qmail 24066 invoked by alias); 28 Mar 2010 15:35:17 -0000 Received: (qmail 23975 invoked by uid 48); 28 Mar 2010 15:35:01 -0000 Date: Sun, 28 Mar 2010 15:35:00 -0000 Subject: [Bug c++/43555] New: wrong address calculation of multidimensional variable-length array element X-Bugzilla-Reason: CC Message-ID: Reply-To: gcc-bugzilla@gcc.gnu.org To: gcc-bugs@gcc.gnu.org From: "skir50 at gmail dot com" Mailing-List: contact gcc-bugs-help@gcc.gnu.org; run by ezmlm Precedence: bulk List-Id: List-Archive: List-Post: List-Help: Sender: gcc-bugs-owner@gcc.gnu.org X-SW-Source: 2010-03/txt/msg02872.txt.bz2 In some cases addressing elements of multidimensioanl variable-length array goes wrong. Consider the program: ------------------------ #include #include int nx,ny; void f(double *x1d,int choice) { double (*x2d)[nx][ny]=(double(*)[nx][ny])x1d; unsigned long delta; // (*x2d)[0][0]=123; // <- this line affects the result if (choice!=0) { delta=&(*x2d)[1][0]-x1d; } else { delta=&(*x2d)[1][0]-x1d; } printf("Choice: %d, Delta: %ld\n",choice,delta); } int main() { double *data; nx=100; ny=100; data=(double*)malloc(nx*ny*sizeof(double)); f(data,0); f(data,1); free(data); return 0; } ------------------------ The idea is to get a difference betweet the address of element [1][0] of 100*100 array and beginning of the array. If it is compiled as *.c by gcc, everiyhing is right, and the output is: $./a.exe Choice: 0, Delta: 100 Choice: 1, Delta: 100 But if is compiled as *.cpp by g++, the output is: $./a.exe Choice: 0, Delta: 18517576 Choice: 1, Delta: 100 So, the error is in obtaining the address of element [1][0] in "else" section in function "f". Analysis of assembler listing showed, that compiler makes a copy of global variable "ny" on a stack and uses that copy to calculate an address of any array element. But for the presented code it makes initialisation of the copy only in the "if" section, when "choice!=0". And if execution flow goes to "else" section, the copy of "ny" remains uninitialized but still used. So, the calculated address of [1][0] is wrong. If we add some array usage before "if" (for example, uncomment the commented line), initialization of the copy of "ny" would be in right place and the result would be correct. -- Summary: wrong address calculation of multidimensional variable- length array element Product: gcc Version: 4.3.4 Status: UNCONFIRMED Severity: normal Priority: P3 Component: c++ AssignedTo: unassigned at gcc dot gnu dot org ReportedBy: skir50 at gmail dot com GCC build triplet: i686-pc-cygwin GCC host triplet: i686-pc-cygwin GCC target triplet: i686-pc-cygwin http://gcc.gnu.org/bugzilla/show_bug.cgi?id=43555