Am 15.03.2014 00:36, schrieb Derek Martin:
> On Sat, Mar 15, 2014 at 12:21:40AM +0100, Matthias Andree wrote:
>> Am 15.03.2014 00:36, schrieb David Laight:
>>> IIRC the warnings come from a property of the symbol in the linker
>>> not the compiler...
> 
> That doesn't make it better. ;)
> 
>> There are strlcpy and strlcat, which take the output buffer capacity,
>> and permit checking if truncation happened or no.
> 
> $ cat strjunk.c
> #include <string.h>
> #include <stdio.h>
> int main(int argc, char **argv)
> {
>     char *a = "foo";
>     char *b = "bar";
>     char  c[7];
>     strlcpy(a, c, 7);
>     strlcat(b, c, 7);
>     printf("%s\n", c);
>     return 0;
> }
> 
> $ gcc -o sj strjunk.c
> [...]/ccW4BTCh.o: In function `main':
> strjunk.c:(.text+0x38): undefined reference to `strlcpy'
> strjunk.c:(.text+0x55): undefined reference to `strlcat'
> collect2: ld returned 1 exit status
> 
> So... not so helpful.
Grab it from any BSD's libc of your choice and move on.
The license is liberal enough for most purposes, the manual page is
there, the code has been debugged already -- and your example is not
helpful because it does _not_ check for lack of capacity.

Quoting FreeBSD's strlcpy(3) manual page:

|      To detect truncation, perhaps while building a pathname,
something like
|      the following might be used:
|
|            char *dir, *file, pname[MAXPATHLEN];
|
|            ...
|
|            if (strlcpy(pname, dir, sizeof(pname)) >= sizeof(pname))
|                    goto toolong;
|            if (strlcat(pname, file, sizeof(pname)) >= sizeof(pname))
|                    goto toolong;

And such recurring idioms can be written as macros if you always use the
same "toolong" jump label, or make it a macro parameter.

It violates some macro style guides, but if it keeps the code readable
and the programmer at actually implementing the checks, it's worthwhile.

Lack of proper exception handling in C (if you discount setjmp.h that
requires spraying volatile over your auto variables) shows that it's
hard to keep a fully error-checked source code readable.

(And in a commercial pre-C89 environment that I use in TMC matters, the
vendor deliberately disabled Microsoft's structured exception handling.
Booo!)

>>> Some system's header files have started forcing programs to check
>>> the error returns from some library functions.
>>> That gets to be a PITA - is some cases you really don't care.
>>
>> Cast to void.
> 
> That's not any less annoying than checking a return value you don't
> care about.  It's 6 useless characters, * many occurences in your
> program.

It is a clear statement "I don't care" that has served to defeat
compiler warnings (including "Unused variable" kind warnings) through
many compiler versions I have used.

Reply via email to