🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.std.c
Article #4726

Re: atexit() and return from main()

#4726
From: Gordon Burditt
Date: Wed, 31 Jan 1996 04:13
41 lines
2356 bytes
>The question I am asking is if:
>    main() calls setjmp() and then calls exit().  An atexit() function
>    calls longjmp() and returns to main().  main() then continues to
>    execute other code. Is the execution of this code defined behaviour
>    (so long as no attempt is made to exit again)?
...
ANSI C Classic 4.6.2.1 The longjmp function

The longjmp function restores the environment saved by the most recent
invocation of the setjmp macro in the same invocation of the program, 
with the corresponding jmp_buf argument.  If there has been no such
invocation, or IF THE FUNCTION CONTAINING THE INVOCATION OF THE SETJMP
MACRO HAS TERMINATED EXECUTION in the interim, the behavior is
undefined.
...
ANSI C Classic 2.1.2.2.3 Program Termination
A RETURN FROM THE INITIAL CALL TO THE MAIN FUNCTION IS EQUIVALENT
TO CALLING THE EXIT FUNCTION with the value returned by the main
function as its argument.
...
I claim that longjmp()ing out of an atexit function into main
causes undefined behavior because main() has already returned
(or, equivalently, called exit()) between the setjmp and
longjmp calls.

In fact, calling exit() may not unwind the stack like returning
from main() does, so you might get away with it, but there's
no guarantee.

>A related question - does undefined behaviour invalidate (make undefined) all 
>defined behaviour that has gone before? If so does this mean that any program 
>that does not exit() or return from main have any defined behaviour?

Undefined behavior can do anything, including causing time to stop or
make it go backwards.  It could even transport you into the Star
Trek universe, where it's well established that cause need not
precede effect.  In the words of Miles O'Brien:  "I hate temporal 
mechanics".

						Gordon L. Burditt
						sneaky.lonestar.org!gordon
Technical Details
Message-ID: <4emq9l$2fn@hammy.lonestar.org>
Path: arc1-ca.pugleaf.net!rowdy.lonestar.org!nemesis!hammy!not-for-mail
References: <4dhfja$j50@fg70.rz.uni-karlsruhe.de> <4diicg$i9e@lyra.csx.cam.ac.uk> <TANMOY.96Jan22084309@qcd.lanl.gov> <DLMLL6.A0H@ukpsshp1.serigate.philips.nl>

Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!rowdy.lonestar.org!nemesis!hammy!not-for-mail
From: gordon@hammy.lonestar.org (Gordon Burditt)
Newsgroups: comp.std.c
Subject: Re: atexit() and return from main()
Date: 30 Jan 1996 22:13:41 -0600
Organization: What organization?
Message-ID: <4emq9l$2fn@hammy.lonestar.org>
References: <4dhfja$j50@fg70.rz.uni-karlsruhe.de> <4diicg$i9e@lyra.csx.cam.ac.uk> <TANMOY.96Jan22084309@qcd.lanl.gov> <DLMLL6.A0H@ukpsshp1.serigate.philips.nl>
NNTP-Posting-Host: localhost.hammy.lonestar.org