0

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!

1
  • You don't initialize coef in term. Is this what you want ? Commented Mar 20, 2015 at 15:57

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.