473,765 Members | 2,047 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

question about "setjmp()"

Hello all,

I used setjmp() in a recent of program of mine (it is not completed, so
I have not the chance to test it out yet). I am not very profocient in
C coding as are some of my co-workers. They (my co-workers) say (with
vehement ardor ;) ) that the usage of setjmp() emplyoyed in function"C"
that was called from function "B" that was called from function "A"
that was called form the main(), will cause havoc in the stack. And it
makes sense, since the longjmp() function/macro has no way of knowing
how high is the stack is, in order to pop out the excess elements in
order to render it as it was when the setjmp() function first set the
"jmpbuf" environment. However, if that were the case the existence of
the setjmp()/longjmp() function pair will not exist.
So, is setjmp()/longjmp() reliable as a "non-local goto", or will it
eventually cause a stack overflow or some other problem?

P.S. I am using the setjmp()/longjmp() only for error handling.

Regards,
-Roger

Oct 1 '06 #1
15 2431
rover8898 wrote:
Hello all,

I used setjmp() in a recent of program of mine (it is not completed, so
I have not the chance to test it out yet). I am not very profocient in
C coding as are some of my co-workers. They (my co-workers) say (with
If you're not proficient with C then I definitely do not recommend playing
around with any *jmp() function. Even when you do become proficient, I'd find
another method. I personally never use them, but that doesn't necessarily
mean they are useless.
Oct 1 '06 #2
It's nice you have coworkers to help you. And they seem to be well
enough informed to realize there is a bit of fiddling required if
you're nested 33 levels deep and want to jump out to the mail program.

But setjmp/longjmp manage this just fine. The basic rigamarole is
setjmp() saves all the CPU registers, including the stack pointer, in
its save area parameter. Then longjmp() mostly just restores those
register values, including the old program counter. Quick and slick
and should probably be used sparingly. But in some cases it's almost
unavoidable.

In more refined languages, like old Pascal, there is no restriction on
goto's, and the compiler generates the right code to do the
inter-procedure jumps. And as a side-benefit, the compiler knows what
files are local to all the intermediate levels, and closes them. Poor
setjmp() doesnt have any way of knowing what files are open, so you'll
have to write your own code to clean up any open files.

Oct 1 '06 #3
Ancient_Hacker wrote:
It's nice you have coworkers to help you. And they seem to be well
enough informed to realize there is a bit of fiddling required if
you're nested 33 levels deep and want to jump out to the mail program.

But setjmp/longjmp manage this just fine. The basic rigamarole is
setjmp() saves all the CPU registers, including the stack pointer, in
its save area parameter. Then longjmp() mostly just restores those
register values, including the old program counter. Quick and slick
and should probably be used sparingly. But in some cases it's almost
unavoidable.

In more refined languages, like old Pascal, there is no restriction on
goto's, and the compiler generates the right code to do the
inter-procedure jumps. And as a side-benefit, the compiler knows what
files are local to all the intermediate levels, and closes them. Poor
setjmp() doesnt have any way of knowing what files are open, so you'll
have to write your own code to clean up any open files.
A.H. touches on one aspect of a larger problem: longjmp()
simply blasts past all the intermediate call levels back to the
setjmp() caller, without giving the skipped levels any chance to
clean up *anything* -- he mentions open files that don't get
closed, but it's the same problem with malloc()ed memory that
doesn't get free()d, painted windows that don't get erased, and
squitted wadgetts that don't get squatted.

In short, despite the word "long" in the name, longjmp() should
really only be used for "short" jumps within a tightly-coupled set
of functions. The functions between the setjmp() and the longjmp()
must be aware of their precarious position and must be written in a
way that requires no cleanup that longjmp() might cancel. Functions
can be written this way, and written usefully, but it is no small
task to write them *and* defend them against future changes. Hence
the advice: Avoid setjmp()/longjmp() most of the time, and when you
do use them, use them "locally." They are not general-purpose.

--
Eric Sosman
es*****@acm-dot-org.invalid
Oct 2 '06 #4
Ancient_Hacker wrote:
>
.... snip ...
>
In more refined languages, like old Pascal, there is no restriction
on goto's, and the compiler generates the right code to do the
inter-procedure jumps. And as a side-benefit, the compiler knows
what files are local to all the intermediate levels, and closes
them. Poor setjmp() doesnt have any way of knowing what files are
open, so you'll have to write your own code to clean up any open
files.
I am very sympathetic with the original C decision to ban goto out
of functions. I did the same in my PascalP, because the end
objective was micro-computers (e.g. 8080) with limited memory. All
functions were packed into segments and consisted of position
independent code. The segments could be freely swapped in and out
of memory, i.e. I had virtual memory for code. The functions were
accessed by a segment jump table, which could hold up to 127 entry
points. Allowing extra-functional jumps would have meant including
rarely used exit points in the table, doubling its size. So I
settled for one terminate system function, the equivalent of a C
exit function.

The result was the ability to run a full one-pass compiler, almost
completely standard compliant, in as little as 5k of object code
space. The disk thrashed a bit by then.

Another thing longjmp can lose is malloced pointers, creating
memory leaks.

--
Some informative links:
<news:news.anno unce.newusers
<http://www.geocities.c om/nnqweb/>
<http://www.catb.org/~esr/faqs/smart-questions.html>
<http://www.caliburn.nl/topposting.html >
<http://www.netmeister. org/news/learn2quote.htm l>
<http://cfaj.freeshell. org/google/>

Oct 2 '06 #5

rover8898 wrote:
Hello all,

I used setjmp() in a recent of program of mine (it is not completed, so
I have not the chance to test it out yet). I am not very profocient in
C coding as are some of my co-workers. They (my co-workers) say (with
vehement ardor ;) ) that the usage of setjmp() emplyoyed in function"C"
that was called from function "B" that was called from function "A"
that was called form the main(), will cause havoc in the stack. And it
makes sense, since the longjmp() function/macro has no way of knowing
how high is the stack is, in order to pop out the excess elements in
order to render it as it was when the setjmp() function first set the
"jmpbuf" environment. However, if that were the case the existence of
the setjmp()/longjmp() function pair will not exist.
So, is setjmp()/longjmp() reliable as a "non-local goto", or will it
eventually cause a stack overflow or some other problem?
Using setjmp() when
you are a few levels down will not cause problems. Part of
the information setjmp() saves is how deep the stack is. All longjmp()
has to do is keep poping elements from the stack until the stack
depth is correct (this may be as simple as resetting the stack
pointer).

On the other hand why are you using setjmp()/longjmp() at all. While I
am told they have their uses, I am also told that they are difficult
to use correctly. I have never used them.
P.S. I am using the setjmp()/longjmp() only for error handling.
Try unwinding the stack yourself. Hijack the return value so
that every function returns SUCCESS of FAILURE. Check the
result of every function call. If the return is FAILURE and
there is something you can do, do it, otherwise clean
up and return FAILURE.

You will soon find yourself writing reams of virtually identical code.
You may ask yourself, "Why isn't the compiler handling this?"
You will learn to appreciate exceptions.

- William Hughes

Oct 2 '06 #6
"Eric Sosman" <es*****@acm-dot-org.invalidwrot e in message
news:1_******** *************** *******@comcast .com...
Ancient_Hacker wrote:
>It's nice you have coworkers to help you. And they seem to be
well
enough informed to realize there is a bit of fiddling required if
you're nested 33 levels deep and want to jump out to the mail
program.

But setjmp/longjmp manage this just fine. The basic rigamarole is
setjmp() saves all the CPU registers, including the stack pointer, in
its save area parameter. Then longjmp() mostly just restores those
register values, including the old program counter. Quick and slick
and should probably be used sparingly. But in some cases it's
almost
unavoidable.

In more refined languages, like old Pascal, there is no restriction
on
goto's, and the compiler generates the right code to do the
inter-procedure jumps. And as a side-benefit, the compiler knows
what
files are local to all the intermediate levels, and closes them.
Poor
setjmp() doesnt have any way of knowing what files are open, so
you'll
have to write your own code to clean up any open files.

A.H. touches on one aspect of a larger problem: longjmp()
simply blasts past all the intermediate call levels back to the
setjmp() caller, without giving the skipped levels any chance to
clean up *anything* -- he mentions open files that don't get
closed, but it's the same problem with malloc()ed memory that
doesn't get free()d, painted windows that don't get erased, and
squitted wadgetts that don't get squatted.

In short, despite the word "long" in the name, longjmp() should
really only be used for "short" jumps within a tightly-coupled set
of functions. The functions between the setjmp() and the longjmp()
must be aware of their precarious position and must be written in a
way that requires no cleanup that longjmp() might cancel.
.... unless, of course, you've called setjmp() just before calling
longjmp(), so that the jumped-to section of code can jump back. This
is, I believe, a standard mechanism for implementing user-mode threads
on platforms that don't natively support them.
Functions can be written this way, and written usefully, but it is no
small task to write them *and* defend them against future changes.
Hence the advice: Avoid setjmp()/longjmp() most of the time, and
when you do use them, use them "locally." They are not general-
purpose.
That sounds like a variation on the rule against using goto. The
problems with set/longjmp() are worse, but in general one should not use
either unless you're savvy enough to explain _why_ the rule doesn't
apply in a particular case and how there's no better (or even possible)
technique. There's virtually always a safer, more elegant way of doing
whatever needs doing.

S

--
Stephen Sprunk "God does not play dice." --Albert Einstein
CCIE #3723 "God is an inveterate gambler, and He throws the
K5SSS dice at every possible opportunity." --Stephen Hawking

--
Posted via a free Usenet account from http://www.teranews.com

Oct 2 '06 #7
Stephen Sprunk wrote:
"Eric Sosman" <es*****@acm-dot-org.invalidwrot e in message
news:1_******** *************** *******@comcast .com...
>[...]
In short, despite the word "long" in the name, longjmp() should
really only be used for "short" jumps within a tightly-coupled set
of functions. The functions between the setjmp() and the longjmp()
must be aware of their precarious position and must be written in a
way that requires no cleanup that longjmp() might cancel.

... unless, of course, you've called setjmp() just before calling
longjmp(), so that the jumped-to section of code can jump back. This
is, I believe, a standard mechanism for implementing user-mode threads
on platforms that don't natively support them.
It might be "standard" in the sense of "widespread ," but it's
not "Standard." 7.12.2.1, paragraph 2, with footnote:

[...] if the function containing the invocation of the
setjmp macro has terminated execution _208) in the interim,
[...] the behavior is undefined.

208) For example, by executing a return statement or because
another longjmp call has caused a transfer to a setjmp
invocation in a function earlier in the set of nested calls.

So the "ping-pong" scheme you describe only works reliably if both
pairs of setjmp()/longjmp() are in the same function -- and if they
are in the same function, why not use goto?

--
Eric Sosman
es*****@acm-dot-org.invalid

Oct 2 '06 #8
In article <45************ ***********@fre e.teranews.com> ,
Stephen Sprunk <st*****@sprunk .orgwrote:
>This
is, I believe, a standard mechanism for implementing user-mode threads
on platforms that don't natively support them.
s/standard mechanism/ancient hack/

-- Richard
Oct 2 '06 #9
rover8898 wrote:
Hello all,

I used setjmp() in a recent of program of mine (it is not completed, so
I have not the chance to test it out yet). I am not very profocient in
C coding as are some of my co-workers. They (my co-workers) say (with
vehement ardor ;) ) that the usage of setjmp() emplyoyed in function"C"
that was called from function "B" that was called from function "A"
that was called form the main(), will cause havoc in the stack. And it
makes sense, since the longjmp() function/macro has no way of knowing
how high is the stack is, in order to pop out the excess elements in
order to render it as it was when the setjmp() function first set the
"jmpbuf" environment. However, if that were the case the existence of
the setjmp()/longjmp() function pair will not exist.
So, is setjmp()/longjmp() reliable as a "non-local goto", or will it
eventually cause a stack overflow or some other problem?

P.S. I am using the setjmp()/longjmp() only for error handling.
You may have a look at:

http://cern.ch/laurent.deniau/html/e...exception.html
http://cern.ch/laurent.deniau/html/o...tml#Exceptions

I haven't really used these codes in my projects, it was more a didactic
approach of the concept. But I am using the same techniques with success
in a much more advanced OO framework.

a+, ld.
Oct 2 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

81
7342
by: Matt | last post by:
I have 2 questions: 1. strlen returns an unsigned (size_t) quantity. Why is an unsigned value more approprate than a signed value? Why is unsighned value less appropriate? 2. Would there be any advantage in having strcat and strcpy return a pointer to the "end" of the destination string rather than returning a
2
1546
by: JS | last post by:
I was told that it was possible to get a list of standard functions i C if I wrote "man"... but where and what should I write after man to get a brief description of the standard functions? JS
77
4035
by: M.B | last post by:
Guys, Need some of your opinion on an oft beaten track We have an option of using "goto" in C language, but most testbooks (even K&R) advice against use of it. My personal experience was that goto sometimes makes program some more cleaner and easy to understand and also quite useful (in error handling cases). So why goto is outlawed from civilized c programmers community. is there any technical inefficiency in that.
40
3156
by: Mark P | last post by:
I'm implementing an algorithm and the computational flow is a somewhat deep. That is, fcn A makes many calls to fcn B which makes many calls to fcn C, and so on. The return value of the outermost fcn is a boolean and there are certain places within the inner functions where it may become apparent that the return value is false. In this case I'd like to halt the computation immediately and return false. My current approach is to have...
4
2133
by: Gestorm | last post by:
Hi all, I found a macro "USE_VAR" in the code of bash-3.2 as follows: /*file: bash-3.2/shell.c*/ 344 USE_VAR(argc); 345 USE_VAR(argv); 346 USE_VAR(env); 347 USE_VAR(code); 348 USE_VAR(old_errexit_flag); 349 #if defined (RESTRICTED_SHELL) 350 USE_VAR(saverst);
27
2528
by: Nate Eldredge | last post by:
Consider the following pseudo-code: #include <opaque.h> struct foo { int a; opaque_t op; int b; };
0
9568
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9404
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
9959
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8833
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7379
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6649
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5277
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5423
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2806
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.