正在静态链接到的库中调用函数(C99)。
在tests.c中:
int ok = solve_equation(&eq, &result);
在poly.c中:
int solve_equation(equation_integer_2 *eq, fraction *result) {...}
指针被传递给结构变量“eq”到函数中。当gdb进入函数时,其中一个struct的变量值
eq->poly->term3->coefficient
与以往不同。从调用代码到库,这个值似乎已经改变了。这是正确的吗?可能导致变化的原因是什么?
Gdb输出:
Breakpoint 1, test_solve_equation_1 () at tests.c:97
97 int ok = solve_equation(&eq, &result);
(gdb) p &eq->poly->term1->coefficient
$15 = (unsigned char *) 0x7fffffffd880 ""
(gdb) p &eq->poly->term2->coefficient
$16 = (unsigned char *) 0x7fffffffd890 "\002\001@"
(gdb) p &eq->poly->term3->coefficient
$17 = (unsigned char *) 0x7fffffffd8a0 ""
(gdb) s
solve_equation (eq=0x7fffffffd8f0, result=0x7fffffffd8d0) at poly.c:64
64 if (eq->poly->term1->coefficient == 0 && eq->poly->term3->coefficient == 0) {
(gdb) p &eq->poly->term1->coefficient
$18 = (unsigned char *) 0x7fffffffd880 ""
(gdb) p &eq->poly->term2->coefficient
$19 = (unsigned char *) 0x7fffffffd890 "\002\001@"
(gdb) p &eq->poly->term3->coefficient
$20 = (unsigned char *) 0x7fffffffd8a0 "\320\330\377\377\377\177"
术语(n)结构的构造如下:
void term_integer_factory(term_integer *t) |#include "number.h"
{ |
t->coefficient = 0; |typedef struct term_fraction
t->degree = 1; |{
}
答案 0 :(得分:0)
像Daniel和user5329483暗示的那样,问题在于struct初始化。函数内部有嵌套的struct初始化。我已将其更改为malloc所有相关结构(使用相应的free
调用)并且它可以正常工作。
它被初始化为:
void polynomial_integer_2_factory(polynomial_integer_2 *p)
{
term_integer t1;
term_integer_factory(&t1);
t1.degree = 2;
p->term1 = &t1;
term_integer t2;
term_integer_factory(&t2);
t2.degree = 1;
p->term2 = &t2;
term_integer t3;
term_integer_factory(&t3);
t3.degree = 0;
p->term3 = &t3;
}
现在它被初始化为:
polynomial_integer_2* create_polynomial_integer_2()
polynomial_integer_2 *p = malloc(sizeof *p);
if (!p) {}
term_integer *t1 = create_term_integer();
t1->degree = 2;
p->term1 = t1;
term_integer *t2 = create_term_integer();
t2->degree = 1;
p->term2 = t2;
term_integer *t3 = create_term_integer();
t3->degree = 0;
p->term3 = t3;
return p;
}