[Gllug] My and my malloc() problems....

Mark Hemment markhe at veritas.com
Mon Dec 31 11:16:42 UTC 2001


On Sun, 30 Dec 2001 tet at accucard.com wrote:

>
> >This is likely only the case if longjmp() is being used, and that little
> >horror should be used as little as possible, IMHO.
>
> I've seen this said many times. Can someone explain:
>
> 1. why setjmp()/longjmp() are so frowned upon

  Usually because programmers do not know its limitations; you cannot rely
on the contents of automatic storage when "setjmp()" returns from a
"longjmp".  This is beacuse a compiler may well have mapped different
automatics to the same memory location (on the stack).
  I've often seen code;
	void bad_func(void)
	{
		int	foo;
		int	bah;
		...
		/* set foo to some value */
		if (setjmp()) {
			if (foo) {
				...
			}
		}
		/* foo isn't touch after here */
		/* "bah" gets some temp location as "foo" */
		/* somewhere after there, a longjmp() is done*/
	}

  which isn't safe.

  To fool the compiler a dummy "goto" can be inserted at the of
"bad_func()" to a label at the head.  This can prevents the compiler from
producing code which clobbers "foo" (note, only "can" as if you're not
careful the compiler can deduce the goto isn't taken and you're back to
square one).
  A few compilers do have an attribute assigned to setjmp() which turns
off certain optimisations for a function which setjmp() appears in, but if
portable code is being written this cannot be relied upon.

  There are other issues (involving signals, and masks, etc), but the
automatic storage is one coders most often forget.

  Also, I've met versions of setjmp() which had bugs (SCO OpenServer in
one of its releases, but it was only a corner-case).

  BTW: The old SVR3.2 kernel had a table for system calls, with a column
in the table indicating if a setjmp() should be done on syscall entry to
allow for quick-and-dirty aborting of the call upon an error/signal.

> 2. what can be used to replace them

  Look at setcontext()/getcontext().  These also work safely with an
alternative signal stack, making them useful for writing psuedo-threaded
code.

Mark


-- 
Gllug mailing list  -  Gllug at linux.co.uk
http://list.ftech.net/mailman/listinfo/gllug




More information about the GLLUG mailing list