------- Comment #20 from dj at redhat dot com  2010-08-12 16:57 -------
Just for fun, I compiled this test case with various levels of optimization. 
It works fine without optimization or with -O1, but segfaults at -O2 or -O3.

That indicates that the program only works by coincidence, not by design -
you've made assumptions about how GCC will interpret your sources, and those
assumptions are wrong.  In this case, your assumption is that "bug_example_2"
will always be a separate function, and will always be called as a separate
function, and thus that you can assume some knowledge of the internals of the
stack layout.

The C language does *not* require that a function which is called, be called as
a separate function, only that the semantics of the call be the same as far as
the C language requires.  The C language allows GCC to implement that function
call in any way it chooses - and GCC chooses to implement it without actually
doing a function call, but by copying the function body to the callee.  At
least, it does when optimizing.  Without optimization, it *happens* to do what
you expect.  It will also do what you expect if bug_example_2 and bug_example
are in separate source files - *then* the "cdecl" standard you refer to
applies, because cross-object calls are limited by the compatibility standards.

However - if you use gcc to link as well, gcc has the option of optimizing
those calls *also*.

So, GCC is "cdecl" compliant because *if* there's a function call, *then* the
*stack* is laid out the same.  However, the "cdecl" standard does *not* require
that your program work, because C allows the optimizer to avoid the actual
function call completely when the callee and caller are in the same scope.

Note: you can tell gcc to not inline a function with __attribute__((noinline))
in which case a call to it is always an actual call to it, but it would be
easier to just use the standard methods for accessing parameters so that it
*always* works.

Also, with full optimization enabled, your code crashes with MSVC also.
Please file a bug report with Microsoft.


-- 


http://gcc.gnu.org/bugzilla/show_bug.cgi?id=45265

Reply via email to