Minor memory leaks in parser
After some memory leak testing on the parser in my own repository i discovered that there are two memory leaks in the getting started code base. Since this affects the getting started code base i created this issue in gitlab in order to better highlight the memory leaks in the code.
The first memory leak is in parser.c in function parse_expression_binary_op
line 288 (click the link to see it in source code)
static struct mcc_ast_expression *
parse_expression_binary_op(struct parser *parser, struct mcc_ast_expression *lhs, int precedence)
{
assert(parser);
enum mcc_ast_binary_op op;
if (accept_with_precedence(MCC_TOKEN_PLUS, &precedence)) {
op = MCC_AST_BINARY_OP_ADD;
} else if (accept_with_precedence(MCC_TOKEN_ASTERISK, &precedence)) {
op = MCC_AST_BINARY_OP_MUL;
} else {
return NULL;
}
struct mcc_ast_expression *rhs = parse_expression(parser, precedence);
if (!rhs) {
error("expression_binary_op: expected rhs expression");
return NULL;
}
struct mcc_ast_expression *result = mcc_ast_new_expression_binary_op(op, lhs, rhs);
if (!result) {
parser_error(parser, MCC_PARSER_ERROR_ALLOCATION_ERROR);
/*-------------------------------------------------*/
/* --> MISSING mcc_ast_delete_expression(rhs); <-- */
/*-------------------------------------------------*/
return NULL;
}
return result;
}
In case the expression rhs
is parsed correctly but allocating the expression result
fails we loose the pointer to rhs
and therefore leak the memory since rhs
is only reachable within the parse_expression_binary_op
function.
The second memory leak is in parser.c in function parse_expression_literal
line 230 (click the link to see it in source code)
static struct mcc_ast_expression *parse_expression_literal(struct parser *parser)
{
assert(parser);
struct mcc_ast_literal *literal = parse_literal(parser);
if (!literal) {
return NULL;
}
struct mcc_ast_expression *result = mcc_ast_new_expression_literal(literal);
if (!result) {
parser_error(parser, MCC_PARSER_ERROR_ALLOCATION_ERROR);
/*--------------------------------------------------*/
/* --> MISSING mcc_ast_delete_literal(literal); <-- */
/*--------------------------------------------------*/
return NULL;
}
return result;
}
In case literal
is parsed correctly but allocating the expression result
fails we loose the pointer to literal
and therefore leak the memory since literal
is onlay reachable within the parse_expression_literal
function.