X
Xavier Roche
Hi folks,
I have a probably rather silly question: is casting a char array in a
char* a potential source of aliasing bug ?
Example: a fonction returning a buffer taken in a circular buffer
typedef struct foo_t foo_t;
struct foo_t {
int index;
char buff[16][8192];
};
static char* getBuff(foo_t *s) {
s->index = ( s->index + 1 ) % 16;
printf("returning s->buff[%d] == %p\n",
s->index, s->buff[s->index]);
return s->buff[s->index];
}
void test(char *a, char *b) {
printf("got pointers: %p %p\n", a, b);
}
int main(void) {
foo_t s = { 0 };
test(getBuff(&s), getBuff(&s));
return 0;
}
The problem is that on Visual C++ 2003, the two returned pointers are
identical when optimizing (!)
Tested with Visual C++ 2003, release mode (optimized)
returning s->buff[1] == 00111F5C
returning s->buff[2] == 00113F5C
got pointers: 00113F5C 00113F5C
Tested with gcc 3.3.4, optimized (O4):
returning s->buff[1] == 0xfffde008
returning s->buff[2] == 0xfffe0008
got pointers: 0xfffde008 0xfffe0008
Is the bug inside this code ? (or inside the compiler ?)
I have a probably rather silly question: is casting a char array in a
char* a potential source of aliasing bug ?
Example: a fonction returning a buffer taken in a circular buffer
typedef struct foo_t foo_t;
struct foo_t {
int index;
char buff[16][8192];
};
static char* getBuff(foo_t *s) {
s->index = ( s->index + 1 ) % 16;
printf("returning s->buff[%d] == %p\n",
s->index, s->buff[s->index]);
return s->buff[s->index];
}
void test(char *a, char *b) {
printf("got pointers: %p %p\n", a, b);
}
int main(void) {
foo_t s = { 0 };
test(getBuff(&s), getBuff(&s));
return 0;
}
The problem is that on Visual C++ 2003, the two returned pointers are
identical when optimizing (!)
Tested with Visual C++ 2003, release mode (optimized)
returning s->buff[1] == 00111F5C
returning s->buff[2] == 00113F5C
got pointers: 00113F5C 00113F5C
Tested with gcc 3.3.4, optimized (O4):
returning s->buff[1] == 0xfffde008
returning s->buff[2] == 0xfffe0008
got pointers: 0xfffde008 0xfffe0008
Is the bug inside this code ? (or inside the compiler ?)