Comment on Never create Ruby strings longer than 23 charactersComments−jbooth14yThis article should really have the word "stack" in it someplace.−skatenerd14yNot knowing much C, I was confused about why malloc() wouldn't get called for the RString structure. This is elucidating:http://www.cs.usfca.edu/~wolber/SoftwareDev/C/CStructs.htmParticularly this part: "// automatic allocation, all fields placed on stack"−metageek14yEven if you're not putting the RString struct on the stack, the embedded string optimization means calling malloc() just once instead of twice.−ori_b14yYou 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 */−teaspoon14yRuby strings are mutable, so you need to be able to free s->data without freeing the RString itself.−ori_b14y s = realloc(s, sizeof(RString));−charliesome14yMRI objects are not relocatable so that won't work if realloc has to move the structure in memory−dchest14yNitpick: sizeof(RString) + length may overflow size_t.
Comments
This article should really have the word "stack" in it someplace.
Not knowing much C, I was confused about why malloc() wouldn't get called for the RString structure. This is elucidating:
http://www.cs.usfca.edu/~wolber/SoftwareDev/C/CStructs.htm
Particularly this part: "// automatic allocation, all fields placed on stack"
Even if you're not putting the RString struct on the stack, the embedded string optimization means calling malloc() just once instead of twice.
You can allocate the string with one malloc:
Ruby strings are mutable, so you need to be able to free s->data without freeing the RString itself.
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.