Pietro
Pietro

Reputation: 788

C - Allocation of struct array inside struct

I've got two structs:

typedef struct Term {
    double coeff;
    int *pow;  
} Term;


typedef struct Polynomial {
    char *vars;
    int num_terms; 
    int num_vars;
    int ordering; 
    Term *terms;
}Polynomial;

my initialization looks like this:

Polynomial *p;
p = malloc(sizeof(*p)); 
p->num_vars = num_vars;
p->num_terms = num_terms;
p->vars = malloc(sizeof(char) * num_vars);
// !!!!! next line
p->terms = malloc(sizeof(Term) * num_terms);
p->ordering = 0;

memcpy(p->vars, vars, sizeof(char) * num_vars); 
for (int i = 0; i < num_terms; i++) {
    p->terms[i].pow = malloc(sizeof(int) * num_vars); 
}

running valgrind:

valgrind --leak-check=yes --track-origins=yes ./poly

tells me:

==22734== 16 bytes in 1 blocks are definitely lost in loss record 1 of 1
==22734==    at 0x4C29F90: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==22734==    by 0x400652: empty_poly (in /home/pietro/tmp/test/poly)
==22734==    by 0x40074E: main (in /home/pietro/tmp/test/poly)

full code is available as gist

How can the struct be correctly initialized?

Thank you!

Upvotes: 0

Views: 161

Answers (1)

juhist
juhist

Reputation: 4314

The error is obvious. You're forgetting to free poly->terms. Try adding free(poly->terms) after free(poly->vars). There is nothing wrong in the initialization, you're not just freeing all of the data you have allocated.

Upvotes: 3

Related Questions