This is not the current version of the class.

Datarep5 Activity

mb1.cc contains the following code for allocating and deallocating memnode objects:

struct memnode_arena {
    memnode* allocate() {
        return new memnode;
    }
    void deallocate(memnode* m) {
        delete m;
    }
};

Which of the following alternate implementations could be used instead without causing errors?

Note. It’s important that the activity use mb1.cc’s definition of memnode:

struct memnode {
    const char* name;
    unsigned number;
};

The recorded lecture mistakenly used mb0.cc’s definition instead.

A.

struct memnode_arena_A {
    memnode* allocate() {
        return (memnode*) malloc(sizeof(memnode));
    }
    void deallocate(memnode* m) {
        free(m);
    }
};

B.

struct memnode_arena_B {
    memnode* allocate() {
        return new memnode;
    }
    void deallocate(memnode* m) {
        free(m);
    }
};

C.

struct memnode_arena_C {
    memnode* allocate() {
        return (memnode*) malloc(sizeof(memnode) + 1000);
    }
    void deallocate(memnode* m) {
        free(m);
    }
};

D.

struct memnode_arena_D {
    memnode* allocate() {
        memnode* m = (memnode*) malloc(sizeof(memnode) * 100);
        return &m[99];
    }
    void deallocate(memnode* m) {
        free(m);
    }
};

E.

struct memnode_arena_E {
    struct annotated_memnode {
        int metadata[40];
        memnode node;
    };
    memnode* allocate() {
        annotated_memnode* am = new annotated_memnode;
        return &am->node;
    }
    void deallocate(memnode* m) {
        uintptr_t m_address = (uintptr_t) m;
        uintptr_t metadata_address = m_address - sizeof(annotated_memnode::metadata);
        annotated_memnode* am = (annotated_memnode*) metadata_address;
        delete am;
    }
};