3 ms·
struct fork_status { enum { ERROR, PARENT, CHILD } state; int ret; }; I think the point of tagged unions (as in OP's example) is that you canno
by barosl 10y ago
struct fork_status {
enum { ERROR, PARENT, CHILD } state;
int ret;
};
I think the point of tagged unions (as in OP's example) is that you cannot access `child` if the call failed. Your example does have an exhaustive check (by a compiler warning), but it doesn't prevent you from misinterpreting `ret` as a pid. Does C have a method to enforce this restriction?
- justincormack 10y agoWell pids should be pid_t not int. System calls should really return two values, return value and errno, but C doesn't handle that very well either.
- masklinn 10y ago> Well pids should be pid_t not int. pid_t isn't a newtype, it's just a typedef, so that doesn't really make a difference. > System calls should really return two values, return value and errno, but C doesn't handle that very well either. Most system calls want to return either, not both. And C doesn't handle that at all.
- sitkack 10y agoAppropriate tangent: Remember that part where null terminated strings save at most three-bytes per string? And if the allocator is long word aligned it saves none-bytes. The first to arrive sets a disproportionate amount of the direction.
- usefulcat 10y agoNot sure how you get that. Let's assume that memory is allocated in sizes that are multiples of 4, and length-prefixed strings have a 4 byte length prefix. str len: c-str bytes: size-prefix bytes: difference: 1 1+1 (4) 4+1 (8) 4 2 2+1 (4) 4+2 (8) 4 3 3+1 (4) 4+3 (8) 4 4 4+1 (8) 4+4 (8) 0 5 5+1 (8) 4+5 (12) 4 6 6+1 (8) 4+6 (12) 4 7 7+1 (8) 4+7 (12) 4 8 8+1 (12) 4+8 (12) 0 So, for example: "ABCDE" as a C-style string would require 5 bytes for the string plus one for the null terminator, which would be satisfied by an allocation of 8 bytes. An equivalent length-prefixed string would require 4 bytes for the prefix plus 5 for the string, which would then be rounded up to 12. The only time the size-prefixed variant doesn't require more memory is when the string length is a multiple of 4. So the length-prefixed version requires an additional 3 bytes on average.
- cmrdporcupine 10y agoMeanwhile this extra memory usage _might_ be relevant on an 8k microcontroller, but even that is questionable given such an application is likely not storing many strings. And the time (and battery! and sanity!) saved by not performing strlen type operations. Worth every byte.
- sitkack 10y agoThanks for the clarification, but I believe neither has said anything in error (replace most with average). I wonder what the breakdown of string lengths in say, clang or nginx is?