0

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)

murage kibicho
  • 546
  • 5
  • 14
  • 1
    You shlould be all set with the way you allocate/free. It looks like a valgrind issue. BTW, a couple of things. First two allocations should be `sizeof(int)`, `sizeof(double)`. You do not allocate space for pointers, but for values. It might cause memory corruption, depending on 32/64 sizes. Also, you do not use `emissionMatrix`. Try to compile with full debugging allowed. valgrind might give you more info. – Serge May 09 '21 at 12:49
  • Thank you so much! What about my third allocation?(sizeof(double*) Is this fine? – murage kibicho May 09 '21 at 12:52
  • 1
    the third allocation is ok, you allocate array of pointers to arrays of double. The fourth (in the loop) is not correct, you allocate the arrays of doubles there. Therfore you need a size of the element, not a pointer to it. So, `sizeof(double)` should be used inside the loop. – Serge May 09 '21 at 13:31

0 Answers0