Am I calling free() correclty on my struct pointer

2019-08-18 15:41发布

问题:

So while testing my struct I use the following method. You can see that I call free on the pointer at the end of the method. Is this right?

void test() {

    VariableVector *labelVector = initVariableVector();
    VariableVector *variableVector = initVariableVector();

    // do some stuff with labelVector and variableVector

    free(labelVector);
    free(variableVector);
}

This is what my struct init methods look like:

Variable* initVariable(char *variableName, char *arrayOfElements,
        int32_t address) {
    Variable* initializedVariable = malloc(sizeof(Variable));
    if (initializedVariable != NULL ) {
        initializedVariable->variableName = variableName;
        initializedVariable->arrayOfElements = arrayOfElements;
        initializedVariable->address = address;
        return initializedVariable;
    } else {
        return NULL ;
    }
}

VariableVector* initVariableVector() {
    VariableVector* initializedVariableVector = malloc(
            sizeof(VariableVector));
    if (initializedVariableVector != NULL ) {
        initializedVariableVector->size = 0;
        initializedVariableVector->capacity = VECTOR_INITIAL_CAPACITY;
        initializedVariableVector->variables = malloc(
                sizeof(Variable) * VECTOR_INITIAL_CAPACITY);
        return initializedVariableVector;
    } else {
        return NULL ;
    }
}

回答1:

Your idea is correct, but your implementation is not.

initVariableVector() does 2 malloc's for one object, but you only do 1 free.

You should have function to destroy it too.

void destroyVariableVector(VariableVector* vector)
{
    if(vector) {
        free(vector->variables);
        free(vector);
    }
}


回答2:

EDIT: You're not checking whether the memory allocation for the member "variables" in structure VariableVector is successful. Which means that even at the end you do not free it manually, so it leads to memory leak.

My advice: Use "init*" functions, but at the same time use "free*" functions. It keeps the code clearer and takes care of all memory releasing.

initVariableVector, the opposite should be freeVariableVector

And the latter function could look like:

void freeVariableVector(VariableVector *vv)
{
    if (vv) {
        if (vv->variables)
            free(vv->variables);
        free(vv);
    }
}