Monday, December 24, 2007

Digging out of history (longjmp is bad)

I had this program written out a long time back, it shows why some constructs are valid, but do not apply well today. In the evolution of C++, we've left behind some holes


 1 #include <stdio.h>
 2 #include <setjmp.h>
 3 #include <string.h>
 4
 5 class C {
 6 private:
 7         char *ptr;
 8 public:
 9         C (const char *name) {
10                 ptr = new char[strlen(name)+1];
11                 printf("constructed C\n");
12         }
13
14         ~C () {
15                 delete [] ptr;
16                 printf("destroyed C\n");
17         }
18 };
19
20 void funfunction(jmp_buf env)
21 {
22         C c("Hello");
23         /*
24          * Do something, at the end expect destructor to be
25          * called
26          */
27         longjmp(env, 1);
28 }
29
30 int main(void)
31 {
32         jmp_buf env;
33         int ret;
34
35         ret = setjmp(env);
36         if (ret) {
37                 printf("Looks like we jumped a long way\n");
38                 return ret;
39         }
40
41         funfunction(env);
42         return 0;
43 }


See if you can find the obvious problem with this code

6 comments:

Gops said...
This comment has been removed by the author.
Gops said...
This comment has been removed by the author.
Gops said...

Geez, what I meant to say was that longjmp only rewinds the stack (clearing local variables) but does not know that the local variable it is clearing in this case has a d'tor that has to be called.

Solution: use exceptions. Always.

Balbir said...

Yes, gops, longjmp is bad and exceptions is probably the solution. The point I was trying to make was that due to legacy we have valid constructs that can and will lead to bad code.

Exceptions are to be discussed in a separate blog item all together. I need to play with them more. I've used them, but I want to play with them

Gops said...

A nice place to start:http://www.boost.org/more/generic_exception_safety.html#reference4

In the references, there is Tom Cargill's classic article on exception safety - a must read!

Balbir said...

Hey, Gops,

Looks like a good URL. Will definitely read in my free time.

Ranking and Unranking permutations

I've been a big fan of Skiena's Algorithm Design Manual , I recently found my first edition of the book (although I own the third ed...