Daniel Marmier d.marmier@bluewin.ch writes:
This is one situation I would like to discuss a bit more. Some code uses a mix of static and dynamic structures containing strings. The static instances have constant strings, the others are xmalloc'd. These strings must be declared char *, since we need to be able to free them. But this prevents us from initializing the static ones with constant strings.
Solution 1 (double casting to avoid constness removal warning) s->name = FAKE_CHARPTR("hello");
Solution 2 (shows clearly that we mix constant/variable and avoids casting): union { const char *c; char *v; } name; s->name.c = "hello";
Can you think of a better solution? What is preferable?
I think this sort of construct should be avoided. If we mix static and allocated data in the same structure, there is a big risk that we will one day try to free static data, with random results. We should change the code so that it doesn't need that, either by storing the static data in a separate structure, or for non performance critical code by allocating a copy of the static data.