/* Collection of code snippets by Arne Vajhøj */
/* (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) */
#include <stdio.h>
#include <stdlib.h>
#include <setjmp.h>

static jmp_buf ctx;

struct Data
{
};

static void os_ressource_allocate()
{
    printf("OS resource allocated\n");
}

static void os_ressource_deallocate()
{
    printf("OS resource deallocated\n");
}

static void m3()
{
    struct Data *o;
    printf("Data memory allocated\n");
    o = malloc(sizeof(struct Data));
    printf("**** Error ****\n");
    printf("Data memory deallocated\n");
    free(o);
    longjmp(ctx, 1);
    return;
}

static void m2()
{
    os_ressource_allocate();
    m3();
    os_ressource_deallocate();
    printf("Normal return\n");
    return;
}

static void m1()
{
    struct Data *o;
    printf("Data memory allocated\n");
    o = malloc(sizeof(struct Data));
    m2();
    printf("Data memory deallocated\n");
    free(o);
    printf("Normal return\n");
    return;
}

int main(int argc, char *argv[])
{
    if(setjmp(ctx))
    {
        printf("Hopefully everything has been deallocated\n");
        return 0;
    }
    else
    {
        m1();
        printf("Normal return\n");
        return 0;
    }
}
