[NTLUG:Discuss] OT: C question
steve
sjbaker1 at airmail.net
Wed May 10 22:04:05 CDT 2006
Fred James wrote:
> All
> I have a C program that if compiled with a "return (0);" as the last
> line in main(), runs correctly but give a "Bus error(core dump)" message.
> If I compile the same C program with a "exit (0);" as the last line in
> main(), the run is also correct, and there is no error message.
>
> What is the difference, please?
>
> K&R says: "Within main, return expr is equivalent to exit(expr). (page
> 164, paragraph 2, "The C Programming Language - Second Edition" by Brian
> W. Kernighan, Dennis M. Ritchie, Prentice Hall Software Series,
> Copyright 1988, 1978, by Bell Telephone Laboratories, Incorporated).
Well, when you 'exit' - the program terminates before 'main' returns.
When you 'return' out of main, control transfers back to a little
machine-code framework that's bolted into your code in the C runtime -
which gets control back to the operating system cleanly.
So it seems that the act of doing that 'return' is causing the problem.
I would guess that you had somehow corrupted the stack contents such
that the return address from 'main' had gotten screwed up. When the
program does an exit, this corruption goes unnoticed - when you 'return'
the return address is needed - so KABLOOIE!
Precise details of what happens and when will be very sensitive to
the number of local variables you have because local variable are
stored on the same section of stack memory as the return addresses
from functions - so something as simple as adding an 'int i;' right
after 'main' could make the problem *seem* to go away - or to make
the symptoms yet harder to find and understand!
It'll also be different on one CPU architecture compared to another - so
it's perfectly possible that you could be 'getting away with it' on a PC
but seeing the problem big time on your MIPS-based SGI gizmo.
I would look for problems where you write to a location off the end of
a locally-declared array - or mis-use the address of a local variable
when the variable itself is out of scope...something like that.
Good luck!
More information about the Discuss
mailing list