From 0a112154522c26abf4f1be4cd8c1aa07364926b5 Mon Sep 17 00:00:00 2001 From: "Yukihiro \"Matz\" Matsumoto" Date: Wed, 7 Feb 2024 17:32:58 +0900 Subject: [PATCH] backtrace.c (packed_backtrace): avoid calling each_backtrace() twice Since the length of the backtrace is at most `ciidx + 1` we can avoid the first call of each_backtrace(). --- src/backtrace.c | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/src/backtrace.c b/src/backtrace.c index a98b80004..83a5180ee 100644 --- a/src/backtrace.c +++ b/src/backtrace.c @@ -106,19 +106,14 @@ packed_backtrace(mrb_state *mrb) if (ciidx >= mrb->c->ciend - mrb->c->cibase) ciidx = mrb->c->ciend - mrb->c->cibase; /* ciidx is broken... */ - /* count the number of backtraces */ - int len = each_backtrace(mrb, ciidx, NULL, NULL); + ptrdiff_t len = ciidx + 1; + backtrace = MRB_OBJ_ALLOC(mrb, MRB_TT_BACKTRACE, NULL); - if (len > 0) { - void *ptr = mrb_malloc(mrb, len * sizeof(struct mrb_backtrace_location)); - backtrace->locations = (struct mrb_backtrace_location*)ptr; - backtrace->len = len; - each_backtrace(mrb, ciidx, pack_backtrace_i, &ptr); - } - else { - backtrace->locations = NULL; - backtrace->len = 0; - } + + void *ptr = mrb_malloc(mrb, len * sizeof(struct mrb_backtrace_location)); + backtrace->locations = (struct mrb_backtrace_location*)ptr; + backtrace->len = each_backtrace(mrb, ciidx, pack_backtrace_i, &ptr); + return (struct RObject*)backtrace; }