Timeline for Implementation of itoa which allocates the string
Current License: CC BY-SA 4.0
4 events
when toggle format | what | by | license | comment | |
---|---|---|---|---|---|
Jul 15, 2021 at 22:53 | comment | added | David G. |
@PeterCordes Well, I did say "lots of optimizations". I wrote my answer just to spell out the leaks in the current code. Personally, for this functionality, I would make a local buffer as a char array, flll it from the right, and return strdup() of my final pointer. (I also wouldn't write this prototype&semantics.) As for the array size, I recommend adding 2, one for the trailing nul, and one for the leading minus sign. Especially since on a 16 bit int platform, your array would be 5 characters and there could be 5 digits, and similarly for a 32 bit int platform, 10 and 10.
|
|
Jul 15, 2021 at 17:42 | comment | added | Peter Cordes |
You don't need an array of int digits in the first place, though, and if you do, it can be a local in automatic storage because the max digit-length of an int is small. Automatic storage is fast and immune to leaks. A local char buf[sizeof(int)*CHAR_BIT / 3] or something would make even more sense (the number of bits in an int / 3 is a loose bound on the max length). (edit: chux's answer already suggests that.)
|
|
Jul 14, 2021 at 3:03 | comment | added | Andrakis | I think this answer addresses the question better than the others, which are more focused on the implementation rather than the memory leaks the poster is concerned about. | |
Jul 14, 2021 at 2:21 | history | answered | David G. | CC BY-SA 4.0 |