Joe Pfeiffer
6/23/2011 11:13:00 PM
Lew Pitcher <lpitcher@teksavvy.com> writes:
> On June 23, 2011 16:07, in comp.lang.c, nospam@nospam.com wrote:
>
> [snip]
>> union MyUnion
>> {
>> char name [100];
>> double dblval;
>> int intVal;
>> };
>>
> [snip]
>>> MyUnion ux;
>>
>> strncpy(ux.name, "C Language", strlen("C Langage")); /* name is set */
>
> As an aside, the above illustrates a common problem found when programmers
> overuse string literals. Here, the strncpy() will result in ux.name being
> set to the string array "C Languag", dropping the final "e"
>
> Do you see why? Hint: it has to do with the string literals.
Ah, I didn't see that one (requires very careful reading!). I was about
to post another, worse bug in the same line: it guarantees no trailing
null at the end of the string (we just had a brief discussion of
strncpy()'s problem in this regard!). Better would be
strncpy(ux.name, "C Language", sizeof(ux.name));
ux.name[sizeof(ux.name)-1] = '\0';
Though this is, of course, inefficient.
Somebody else suggested using strcpy(); since the string being copied is
a literal a good code review will would then establish no buffer
overrun.