7 ms·
> strftime() has to write to a string of a fixed length it can not dynamically allocate (This is less legacy than it is bad design) There's good reason for thi
by shakna 2y ago
> strftime() has to write to a string of a fixed length it can not dynamically allocate (This is less legacy than it is bad design)
There's good reason for this. I disagree that it's a bad design.
strftime can legitimately produce zero-length strings, in a non-error state. You do not want an allocation on the heap, that is empty.
You'd end up with more error states to track, and more confusion around whether the function had succeeded. (Especially when using %c).
- CamperBob2 2y agoA zero-length C string is still one byte long, for better or for worse.
- shakna 2y agoRight. So you have an extra byte you need to free. One that you can't introspect, and reading will cause a memory fault, because it won't be NULL-terminated (0-length means 0 length). And not freeing, because the assumption of 0-length is violated, leads to a memory leak. So instead of just checking one return value, now you have to check two. And people are not great at even handling a single NULL check. Few people check malloc's return, as awful as that is. Design should be intuitive as possible. You can't assume they'll even look at a manpage. If something returns a length, then people assume that length is what will be allocated. A valid 0-length time string, violates that assumption, and will cause problems down the line. If someone is forced to do the allocation themselves, then there's a greater chance they'll actually notice that they need to free it.
- CamperBob2 2y agoWhat? No, the null terminator is the single byte in question. That's how an empty string is represented in C. It's not the same thing as a NULL pointer, as you may be thinking.