diff --git a/mpc.c b/mpc.c index fc560bf..a3d6c7b 100644 --- a/mpc.c +++ b/mpc.c @@ -1046,12 +1046,26 @@ enum { #define MPC_MAX_RECURSION_DEPTH 1000 +static mpc_result_t *grow_results(mpc_input_t *i, int j, mpc_result_t *results_stk, mpc_result_t *results){ + mpc_result_t *tmp_results = results; + + if (j == MPC_PARSE_STACK_MIN) { + int results_slots = j + j / 2; + tmp_results = mpc_malloc(i, sizeof(mpc_result_t) * results_slots); + memcpy(tmp_results, results_stk, sizeof(mpc_result_t) * MPC_PARSE_STACK_MIN); + } else if (j >= MPC_PARSE_STACK_MIN) { + int results_slots = j + j / 2; + tmp_results = mpc_realloc(i, tmp_results, sizeof(mpc_result_t) * results_slots); + } + + return tmp_results; +} + static int mpc_parse_run(mpc_input_t *i, mpc_parser_t *p, mpc_result_t *r, mpc_err_t **e, int depth) { int j = 0, k = 0; mpc_result_t results_stk[MPC_PARSE_STACK_MIN]; mpc_result_t *results; - int results_slots = MPC_PARSE_STACK_MIN; if (depth == MPC_MAX_RECURSION_DEPTH) { @@ -1176,14 +1190,7 @@ static int mpc_parse_run(mpc_input_t *i, mpc_parser_t *p, mpc_result_t *r, mpc_e while (mpc_parse_run(i, p->data.repeat.x, &results[j], e, depth+1)) { j++; - if (j == MPC_PARSE_STACK_MIN) { - results_slots = j + j / 2; - results = mpc_malloc(i, sizeof(mpc_result_t) * results_slots); - memcpy(results, results_stk, sizeof(mpc_result_t) * MPC_PARSE_STACK_MIN); - } else if (j >= results_slots) { - results_slots = j + j / 2; - results = mpc_realloc(i, results, sizeof(mpc_result_t) * results_slots); - } + results = grow_results(i, j, results_stk, results); } *e = mpc_err_merge(i, *e, results[j].error); @@ -1198,14 +1205,7 @@ static int mpc_parse_run(mpc_input_t *i, mpc_parser_t *p, mpc_result_t *r, mpc_e while (mpc_parse_run(i, p->data.repeat.x, &results[j], e, depth+1)) { j++; - if (j == MPC_PARSE_STACK_MIN) { - results_slots = j + j / 2; - results = mpc_malloc(i, sizeof(mpc_result_t) * results_slots); - memcpy(results, results_stk, sizeof(mpc_result_t) * MPC_PARSE_STACK_MIN); - } else if (j >= results_slots) { - results_slots = j + j / 2; - results = mpc_realloc(i, results, sizeof(mpc_result_t) * results_slots); - } + results = grow_results(i, j, results_stk, results); } if (j == 0) {