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
Post a Comment