Scoping question in C

Francois Ouellette fouellet-cpI+UMyWUv9BDgjK7y7TUQ at public.gmane.org
Mon Jun 13 15:44:14 UTC 2005


>> Note: NEVER use strcpy().  Use only strncpy(), and always provide a
>> correct length parameter, lest you summon a buffer overflow demon.  ;)
>
> strcpy() is perfectly safe if you know the length of the string being
> copied.  There is a faction which argues that that is the preferable
> approach.
>
> strncpy() is actually not much of an improvement, because if the string
> being copied does overflow the destination, strncpy() won't NUL-terminate
> it, which is likely to mess up the *next* use of that string.
>
> If you want to delegate the length checking to the copy routine, what you
> want is something like OpenBSD's strlcpy() (not generally available in
> Linux, alas, due to the religious beliefs of the glibc maintainers).

Ahhh, good old C dilemmas!

A safe approach is to check the length of the source string, and zero-fill
the destination string when using strncpy, after checking that it will
fit!

Another is to use sprintf which returns the last position written in the
string and allows size checking too.

 François Ouellette
<fouellet-cpI+UMyWUv9BDgjK7y7TUQ at public.gmane.org>

--
The Toronto Linux Users Group.      Meetings: http://tlug.ss.org
TLUG requests: Linux topics, No HTML, wrap text below 80 columns
How to UNSUBSCRIBE: http://tlug.ss.org/subscribe.shtml





More information about the Legacy mailing list