Darryl Okahata <darrylo(a)soco.agilent.com> writes:
[ Discussion redirected to xemacs-beta. ]
Zajcev Evgeny <zevlg(a)yandex.ru> wrote:
> As you can see function CPTR1 just does nothing, even without
> optimisation flags, gcc optimized this function to just return. So no
Gcc 3.4.2 is hideously broken if it's doing crud like that.
Yes, but what we have is what we have. Here is my investigations:
---- file m.c ----
void
cptr1(void *ptr, unsigned int len)
{
if (len > 1)
/* If we can, try to avoid problems with super-optimizing compilers
that might decide that memcmp (ptr, ptr, len) can be optimized
away since its result is always 1. */
memcmp (ptr, (char *) ptr + 1, len - 1);
else
memcmp (ptr, ptr, len);
}
void
cptr2(void *ptr, unsigned int len)
{
while (len-- > 0) {
char a = ((char*)ptr)[len];
if (a == '1')
/* pass */;
}
}
int
main()
{
void *ptr = (void*)10;
cptr1(ptr, 10);
printf("cptr1\n");
cptr2(ptr, 10);
printf("cptr2\n");
return 0;
}
---- m.c ends here ---
[0][~]$ gcc342 -o m m.c
[0][~]$ ./m
cptr1
zsh: segmentation fault (core dumped) ./m
[139][~]$ gcc342 -O -o m m.c
[0][~]$ ./m
cptr1
cptr2
[0][~]$ gcc295 -o m m.c
[0][~]$ ./m
zsh: segmentation fault (core dumped) ./m
[139][~]$ gcc295 -O -o m m.c
[0][~]$ ./m
cptr1
cptr2
[0][~]$
CPTR1 works only with gcc295 without any optimisation flags. CPTR2
works on gcc295 and gcc342 without optimisation flags.
So even CPTR2 is does not cheats gcc optimisations fully, finally i
was able to get good results with next CPTR2:
void
cptr2(void *ptr, unsigned int len)
{
while (len-- > 0) {
char a = ((char*)ptr)[len];
if (a == '1')
((char*)ptr)[len] = a;
}
}
[0][~]$ gcc342 -o m m.c
[0][~]$ ./m
cptr1
zsh: segmentation fault (core dumped) ./m
[139][~]$ gcc342 -O -o m m.c
[0][~]$ ./m
cptr1
zsh: segmentation fault (core dumped) ./m
[139][~]$ gcc342 -O3 -o m m.c
[0][~]$ ./m
cptr1
zsh: segmentation fault (core dumped) ./m
[139][~]$ gcc295 -o m m.c
[0][~]$ ./m
zsh: segmentation fault (core dumped) ./m
[139][~]$ gcc295 -O -o m m.c
[0][~]$ ./m
cptr1
zsh: segmentation fault (core dumped) ./m
[139][~]$ gcc295 -O3 -o m m.c
[0][~]$ ./m
cptr1
zsh: segmentation fault (core dumped) ./m
[139][~]$
As you see new CPTR2 does the job with both gcc342 and gcc 295 and
any optimisation flags.
Thanks!
--
lg