Home:ALL Converter>C: Moving free statements into separate function causes memory leak

C: Moving free statements into separate function causes memory leak

Ask Time:2018-06-13T21:32:03         Author:DanielJ

Json Formatter

I have the following structure and initialisation of it in a C file:

struct Lattice {
    int length;
    int** latt;
};

struct Lattice* Create(int size){
    struct Lattice latt;
    int i,j,k,l;

    latt.length = size;
    latt.latt = malloc(sizeof(int*) * latt.length);

    for(i=0; i<latt.length; i++){
        latt.latt[i] = malloc(sizeof(int) * latt.length);
    }

        for(j=0; j<latt.length; j++){
            for(k=0; k<latt.length; k++){
                latt.latt[j][k] = 0;
            }
        }

    struct Lattice* lattp = &latt;
    return lattp;

And I also have the memory freeing function:

void Destroy(struct Lattice* lattp){
    int l;
    for (l=0; l<(lattp->length); l++){
        free(lattp->latt[l]);
    }
    free(lattp->latt);
}

But whenever I run the code:

int main(){
    struct Lattice* lattp = Create(5);
    Destroy(lattp);

    return 0;
}

I get a memory leak (according to Valgrind it is 40 bytes definitely lost and a further 80 indirectly lost, if this makes any difference).

But if I have identical code except that I write the free statements, which are identical to the ones in Destroy, into Create (and modify the return statements appropriately), I don't get a memory leak. Why does moving the free statements into a separate function cause a memory leak?

Author:DanielJ,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/50838571/c-moving-free-statements-into-separate-function-causes-memory-leak
yy