I was unable to free my struct correctly. How should I change my destroy function? I'm learning C but I'm having a hard time with malloc. I get a valgrind error even after running my destroy function. I create my struct like this:
typedef struct hmm *HMM;
struct hmm
{
int transitionBase;
int emissionBase;
int *elementCounter;
double *startMatrix;
double **transitionMatrix;
double **emissionMatrix;
};
HMM CreateHmm(int transitionBase, int emissionBase)
{
HMM hidden;
hidden = malloc(sizeof(*hidden));
hidden->transitionBase = transitionBase;
hidden->emissionBase = emissionBase;
hidden->elementCounter = calloc(transitionBase, sizeof(int*));
hidden->startMatrix = calloc(transitionBase, sizeof(double*));
hidden->transitionMatrix = malloc(sizeof(double*) * transitionBase);
for(int i = 0; i < transitionBase; i++)
{
hidden->transitionMatrix[i] = calloc(transitionBase, sizeof(double*));
}
return hidden;
}
and this is my destroy function
void DestroyHMM(HMM hidden)
{
for(int i = 0; i < hidden->transitionBase; i++)
{
free(hidden->transitionMatrix[i]);
}
free(hidden->elementCounter);
free(hidden->startMatrix);
free(hidden->transitionMatrix);
free(hidden);
}
The error is
184 (40 direct, 144 indirect) bytes in 1 blocks are definitely lost in loss record 6 of 6
==7325== at 0x483B7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==7325== by 0x1092C5: CreateHmm (in /home/murage/Desktop/bb/processor.o)
==7325== by 0x109F92: main (in /home/murage/Desktop/bb/processor.o)