Memory leak with dynamic array

bearophile bearophileHUGS at lycos.com
Sun Apr 11 07:21:43 PDT 2010


One more small thing I was forgetting. In my dlibs1 there are functions similar to:


T[][] NewVoidGCMatrix(T)(int nr, int nc) {
    // Part of the code by Marius Muja <mariusm at cs.ubc.ca>
    assert(nr > 0, "NewVoidCGMatrix: nr must be > 0.");
    assert(nc > 0, "NewVoidCGMatrix: nc must be > 0.");
    void* mem = cast(void*)gcmalloc(nr * (T[]).sizeof + nr * nc * T.sizeof);
    hasNoPointers(mem);
    T[]* index = cast(T[]*)mem;
    T* mat = cast(T*)(mem + nr * (T[]).sizeof);

    for (int i = 0; i < nr; ++i) {
        index[i] = mat[0 .. nc];
        mat += nc;
    }

    return index[0 .. nr];
}

void delVoidGC(T)(ref T[] a) {
    gcrealloc(a.ptr, 0);
    a = null;
}


They allow to allocate only one chunk of memory for a matrix, and in some situations they give a little more performance (because they give a little more CPU cache coherence). I guess such functions can't be used in D2. But maybe once I know the underlying data structure I can write something similar for D2 too.

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list