Am I calling free() correclty on my struct pointer

2019-08-18 15:34发布

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 ;
    }
}

2条回答
戒情不戒烟
2楼-- · 2019-08-18 15:58

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);
    }
}
查看更多
神经病院院长
3楼-- · 2019-08-18 16:10

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);
    }
}
查看更多
登录 后发表回答