Aliasing bug when casting char[] into char* ?

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 ?)

[Xpost to comp.lang.c, comp.std.c, FU2 to comp.std.c]
 
X

Xavier Roche

Arthur said:
This is the interesting line. Are we guaranteed that the two
invocations of 'getBuff' do not interleave in any way? I think
we are, because 6.5.2.2#10 guarantees a sequence point before
each function call. Therefore, MSVC++ is wrong.

Thanks, good catch! - the inlining of the function appears to be the
problem. Even though the function call order is undefined, I also
suspect that the function call should guarantee a sequence point.

The only workaround to this feature seems to use the MSVC-specific
keyword '__declspec(noinline)'

(I just checked, and this "optimization" has been removed for MSVC 2005,
and is only in MSVC2003 (*and* not in earlier releases))
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top