4 ms·
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/Soft
by skatenerd 15y ago
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 http://www.cs.usfca.edu/~wolber/SoftwareDev/C/CStructs.htm
Particularly this part:
"// automatic allocation, all fields placed on stack"
- metageek 15y agoEven if you're not putting the RString struct on the stack, the embedded string optimization means calling malloc() just once instead of twice.
- ori_b 15y agoYou 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 */
- teaspoon 15y agoRuby strings are mutable, so you need to be able to free s->data without freeing the RString itself.
- ori_b 15y agos = realloc(s, sizeof(RString));
- charliesome 15y agoMRI objects are not relocatable so that won't work if realloc has to move the structure in memory
- dchest 15y agoNitpick: sizeof(RString) + length may overflow size_t.