4 ms·
Say, somebody allocated one of the strings with malloc or strdup and put a free(), but mixed up when to call free() and when not.
by perdunov 12y ago
Say, 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.
- Ma8ee 12y agoAnd how is this different from char* x; ... if (/*smth*/) { x = "Hello"; } else { x = strdup("Hello"); } ... if (/*smth*/) { free(x); } ? Maybe I'm slow, but I don't see how the union makes a difference.
- perdunov 12y agoThe difference is that the code may try to execute x = "Hello", and then call free(y) (in case the condition is messed up). So the code will try to free() the pointer to a string literal (because they share the same memory location in the union).
- Ma8ee 12y agoYes, but you can do x = "Hello" and then call free(x) and get the exact same error without the union. The union doesn't make a difference.
- perdunov 12y agoThe union does make a difference. The point I was making is that char*'s (and other pointer types as well) in unions make it harder to track ownership and lifetime by introducing implicit dependencies between data and increasing complexity with more code paths. It's much easier to reason about the correctness of the code, when the fields of the data structures are mutated linearly and independently. This is especially important when the code is maintained by a number of people over long time. Unfortunately, the C language does not have the capability to automatically check the correctness of memory management and object lifetimes, so the developer has to do their best to ensure the correctness of the code. In doing so, some coding practices can be better than others. I am talking about generally good and bad coding practices here, not about the formal correctness of that particular piece of code. If some code works, then obviously it is correct, even if the code is obfuscated, non-human-readable or maintainable.