Scoping question in C

Chris F.A. Johnson cfaj-uVmiyxGBW52XDw4h08c5KA at public.gmane.org
Mon Jun 13 17:39:45 UTC 2005


On Mon, 13 Jun 2005, Taavi Burns wrote:

> On 6/13/05, Francois Ouellette <fouellet-cpI+UMyWUv9BDgjK7y7TUQ at public.gmane.org> wrote:
>> 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!
>
> But what if the source string is (somehow) not NULL-terminated!  ;)

     Then, by definition, it is not a string.

> Given a source string of unknown size and a destination string that
> needs to be X chars:
>
> char *source;
> char dest[X+1] = {0}; // zero-initialise the whole string
>
> strncpy(dest, source, X);
>
> That will always produce a NULL-terminated string, and has less chance
> of taking too long a walk off of source (though if source were very
> small, it still could; something like electricfence helps with
> finding/debugging this kind of bug).

      What's the point in trying to find one method to do different
      things?

      If you know that the string will fit in the destination, just use
      strcpy(). If you don't use one of the other methods that has been
      given, depending on the situation.

-- 
     Chris F.A. Johnson                     <http://cfaj.freeshell.org>
     ==================================================================
     Shell Scripting Recipes: A Problem-Solution Approach, 2005, Apress
     <http://www.torfree.net/~chris/books/cfaj/ssr.html>
--
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