1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// CREDIT:  Pete Kirkham @ http://stackoverflow.com/a/1692864/500022 CC-BY-SA-3.0
#include <stdio.h>
#include <setjmp.h>
#include <string.h>
#include <stdlib.h>

void foo ( char** data ) ;
void handle ( char* data ) ;
jmp_buf env;

int main () {
    char* data = 0;

    int res = setjmp ( env ); 
    // stored for demo purposes.  in portable code do not store the result, but
    // test it directly.

    printf ( "setjmp returned %d\n", res );

    if ( res == 0 ) {
        foo ( &data );
    }
    else {
        handle ( data );
    }

    return 0;
}


void foo ( char** data )
{
    *data = malloc ( 32 );

    printf ( "in foo\n" );

    strcpy ( *data, "Hello World" );

    printf ( "data = %s\n", *data );

    longjmp ( env, 42 );
}

void handle ( char* data )
{
    printf ( "in handler\n" );

    if ( data ) {
        free ( data );
        printf ( "data freed\n" );
    }
}

© Copyright 2016 Alexander J. Quinn         This content is protected and may not be shared, uploaded, or distributed.