我一直遇到一个无法解决的分段错误。导致分段错误的函数如下所示:
Expression *IntegerLiteral_init(int intgr) {
Expression *the_exp = safe_alloc(sizeof(Expression));
the_exp->type = expr_IntegerLiteral;
the_exp->expr->intgr = intgr;
the_exp->exec_count = 0;
return the_exp;
}
表达式的定义:
typedef struct {
expr_type type;
u_expr *expr;
int exec_count;
} Expression;
u_expr和expr_type已定义:
typedef union {
char *ident;
int intgr;
} u_expr;
typedef enum {
expr_Identifier,
expr_IntegerLiteral
} expr_type;
expr_type
是一个由expr_IntegerLiteral
和expr_Identifier
组成的枚举。
根据GDB的显示,段错误是在这一行引起的:the_exp->expr->intgr = intgr;
。奇怪的是,并不总是会导致段错误-只有当我以这种方式调用函数时才会出现:
Expression *e = IntegerLiteral_init(0);
但在程序的另一个部分,我使用以下方式调用它:
Expression *e;
...
e = IntegerLiteral_init(
(int)strtol(num_str, (char **)NULL, 10));
这段代码可以正常运行。 num_str
是从某个输入中解析出的字符串,其值为"0"
.
如果给定的intgr
参数相同,我不明白为什么调用 IntegerLiteral_init()
的上下文会影响此段错误。如果有人能够解释一下,我将非常感激。
Expression
更改为按值持有u_expr
,然后使用结构引用运算符.
代替结构解引用运算符->
。即the_exp->expr.intgr = intgr;
可以改为the_exp.expr.intgr = intgr;
。 - simonc