Skip to content

Comment on Never create Ruby strings longer than 23 charactersparent

Comments

You can allocate the string with one malloc:

    RString *s = malloc(sizeof(RString) + length); /* allocate 'length' bytes extra memory past the end of 's' */
    s->data = s + 1; /* to the extra memory past the start of the string struct */

Ruby strings are mutable, so you need to be able to free s->data without freeing the RString itself.

    s = realloc(s, sizeof(RString));

MRI objects are not relocatable so that won't work if realloc has to move the structure in memory

Nitpick: sizeof(RString) + length may overflow size_t.

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.