3 ms·
A zero-length C string is still one byte long, for better or for worse.
by CamperBob2 2y ago
A 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.