Skip to content

Commit 8a9a241

Browse files
committed
Fix memory error on str_buf_cat
Modify from nofree to embed string
1 parent 30b6648 commit 8a9a241

1 file changed

Lines changed: 12 additions & 5 deletions

File tree

src/string.c

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -695,14 +695,21 @@ mrb_str_modify(mrb_state *mrb, struct RString *s)
695695
}
696696
if (RSTR_NOFREE_P(s)) {
697697
char *p = s->as.heap.ptr;
698+
mrb_int len = s->as.heap.len;
698699

699-
s->as.heap.ptr = (char *)mrb_malloc(mrb, (size_t)s->as.heap.len+1);
700+
RSTR_UNSET_NOFREE_FLAG(s);
701+
if (len < RSTRING_EMBED_LEN_MAX) {
702+
RSTR_SET_EMBED_FLAG(s);
703+
RSTR_SET_EMBED_LEN(s, len);
704+
}
705+
else {
706+
s->as.heap.ptr = (char *)mrb_malloc(mrb, (size_t)len+1);
707+
s->as.heap.aux.capa = len;
708+
}
700709
if (p) {
701-
memcpy(RSTR_PTR(s), p, s->as.heap.len);
710+
memcpy(RSTR_PTR(s), p, len);
702711
}
703-
RSTR_PTR(s)[s->as.heap.len] = '\0';
704-
s->as.heap.aux.capa = s->as.heap.len;
705-
RSTR_UNSET_NOFREE_FLAG(s);
712+
RSTR_PTR(s)[len] = '\0';
706713
return;
707714
}
708715
}

0 commit comments

Comments
 (0)