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 ;
}
}
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:
Your idea is correct, but your implementation is not.
initVariableVector()
does 2malloc
's for one object, but you only do 1free
.You should have function to destroy it too.