This is the mail archive of the
gcc-bugs@gcc.gnu.org
mailing list for the GCC project.
[Bug c++/43555] New: wrong address calculation of multidimensional variable-length array element
- From: "skir50 at gmail dot com" <gcc-bugzilla at gcc dot gnu dot org>
- To: gcc-bugs at gcc dot gnu dot org
- Date: 28 Mar 2010 15:35:01 -0000
- Subject: [Bug c++/43555] New: wrong address calculation of multidimensional variable-length array element
- Reply-to: gcc-bugzilla at gcc dot gnu dot org
In some cases addressing elements of multidimensioanl variable-length array
goes wrong. Consider the program:
------------------------
#include<stdio.h>
#include<stdlib.h>
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