4 ms·
Great idea, but oops... the data structure thing_t is hideous. It is a "god object" for anything where differently purposed members are union'd. Also, putting c
by perdunov 12y ago
Great idea, but oops... the data structure thing_t is hideous. It is a "god object" for anything where differently purposed members are union'd. Also, putting char*'s into a union is a terrible idea.
- masklinn 12y ago> It is a "god object" for anything where differently purposed members are union'd. Also, putting char*'s into a union is a terrible idea. They're not differently purposed, the union is just used to define more contextual labels for equivalent fields, and thus make initialisation more readable within each domain.
- perdunov 12y agoThere are three data structures unsystematically blended into one (that is, one cannot unambiguously tell which fields go into which "virtual" type, and cannot formally check the correctness). The name thing_t is indicative that you indeed cannot really tell what that entity is. This kind of data structure design begs for errors, while being conceptually wrong.
- masklinn 12y ago> There are three data structures unsystematically blended into one The point is that they're not three completely separate data structures, they're a single data structure with context-dependent field labelling.
- perdunov 12y agoI get your point, but how to tell "labelling" from typing? Typing depends on semantics. This particular example only works out because the types are all strings, which is a case of sort of loose typing often used in programming. It could've been like this: typedef struct { union { company_t * company; school_t * school; project_t * project; }; union { address_t * location; url_t * url; }; etc.
- Ma8ee 12y agoWhy is putting char* into a union a bad idea?
- perdunov 12y agochar* points to some mutable buffer of char's that is supposed to be allocated somewhere. In this particular case they are assigned string literals, but in general it would be quite easy for someone to break consistency of allocations/deallocations in such code.
- masklinn 12y agoGiven all unioned members are char*, where would the issue come from?
- perdunov 12y agoSay, somebody allocated one of the strings with malloc or strdup and put a free(), but mixed up when to call free() and when not.
- masklinn 12y agoOK but that's an issue with using char* where does the union issue come in? I could understand an issue with a union between char* and, say, int or some other pointer, but I don't see what specific issue would arise from a union between the exact same pointer types.
- perdunov 12y agounion { char* x; char* y; }; ... if (/*smth*/) { x = "Hello"; } else { y = strdup("Hello"); } ... if (/*smth*/) { free(y); } It is possible to screw up the condition to calling free(), especially in more involved code.
- 12y ago