C - struct中struct元素的分配

时间:2015-03-20 15:45:09

标签: c arrays struct

我有两个结构:

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


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

我的初始化看起来像这样:

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); 
}

运行valgrind:

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

告诉我:

==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)

完整代码可用gist

如何正确初始化结构?

谢谢!

1 个答案:

答案 0 :(得分:3)

错误很明显。你忘了免费使用poly-gt;术语。尝试在免费后添加免费(poly-&gt;术语)(poly-&gt; vars)。初始化没有任何问题,您不仅可以释放已分配的所有数据。