Comment by brabel
My point was that if you’re going to allocate anyway what was the point of allocating the original on the stack? You wouldn’t need the duplicate if you malloc that.
My point was that if you’re going to allocate anyway what was the point of allocating the original on the stack? You wouldn’t need the duplicate if you malloc that.
Yes, that is right. The only reason I did it this way was, because I wanted to demonstrate a naive implementation, I wouldn't commit that, but I wouldn't commit leftpad at all.
Allocating on the stack is pretty cheap, it's only a single instruction to move the stack pointer. The compiler is likely to optimize it away completely. When doing more complicated things, where you don't build the string linearly allocating on the stack first can be likely cheaper, since the stack memory is likely in cache, but a new allocation isn't. It can also make the code easier, since you can first do random stuff on the stack and then allocate on the heap once the string is complete and you know its final size.