Comment by brabel

Comment by brabel 5 days ago

4 replies

Not a C expert but you’re using a dynamic array right on the stack, and then returning the duplicate of that. Shouldn’t that be Malloc’ed instead?? Is it safe to return the duplicate of a stack allocated array, wouldn’t the copy be heap allocated anyway? Not to mention it blows the stack and you get segmentation fault?

1718627440 5 days ago

> and then returning the duplicate of that. Shouldn’t that be Malloc’ed instead??

Like the sibling already wrote, that's what strdup does.

> Is it safe to return the duplicate of a stack allocated

Yeah sure, it's a copy.

> wouldn’t the copy be heap allocated anyway?

Yes. I wouldn't commit it like that, it is a naive implementation. But honestly I wouldn't commit leftpad at all, it doesn't sound like a sensible abstraction boundary to me.

> Not to mention it blows the stack and you get segmentation fault?

Yes and I already mentioned that in my comment.

---

> dynamic array right on the stack

Nitpick: It's a variable length array and it is auto allocated. Dynamic allocation refers to the heap or something similar, not already done by the compiler.

lionkor 5 days ago
  • brabel 4 days ago

    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.

    • 1718627440 4 days ago

      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.