Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 7.10 setjmpandlongjmpFunctions 219


If we compile and test the program in Figure7.13, with and without compiler
optimizations, the results aredifferent:
$gcc testjmp.c compile without any optimization
$./a.out
in f1():
globval = 95, autoval = 96, regival = 97, volaval = 98, statval = 99
after longjmp:
globval = 95, autoval = 96, regival = 97, volaval = 98, statval = 99
$gcc -O testjmp.c compile with full optimization
$./a.out
in f1():
globval = 95, autoval = 96, regival = 97, volaval = 98, statval = 99
after longjmp:
globval = 95, autoval = 2, regival = 3, volaval = 98, statval = 99
Note that the optimizations don’t affect the global, static, and volatile variables; their
values after thelongjmparethe last values that they assumed. Thesetjmp( 3 )manual
page on one system states that variables stored in memory will have values as of the
time of thelongjmp,whereas variables in the CPU and floating-point registers are
restored to their values whensetjmpwas called. This is indeed what we see when we
runthe program in Figure7.13. Without optimization, all five variables arestored in
memory (theregisterhint is ignored forregival). When we enable optimization,
bothautovalandregivalgo into registers, even though the former wasn’t declared
register,and thevolatilevariable stays in memory.The important thing to realize
with this example is that you must use thevolatileattribute if you’rewriting
portable code that uses nonlocal jumps. Anything else can change from one system to
the next.
Someprintfformat strings in Figure7.13 arelonger than will fit comfortably for
display in a programming text. Instead of making multiple calls toprintf, we rely on
ISO C’s string concatenation feature, wherethe sequence
"string1" "string2"
is equivalent to
"string1string2"

We’ll return to these two functions,setjmpandlongjmp, in Chapter 10 when we
discuss signal handlers and their signal versions:sigsetjmpandsiglongjmp.

Potential Problem with Automatic Variables


Having looked at the way stack frames areusually handled, it is worth looking at a
potential error in dealing with automatic variables. The basic rule is that an automatic
variable can never be referenced after the function that declared it returns. Numerous
warnings about this can be found throughout the UNIX System manuals.
Figure7.14 shows a function calledopen_datathat opens a standardI/O stream
and sets the buffering for the stream.
Free download pdf