Scoping question in C

Taavi Burns jaaaarel-Re5JQEeQqe8AvxtiuMwx3w at public.gmane.org
Mon Jun 13 17:20:48 UTC 2005


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!  ;)

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).

-- 
taa
/*eof*/
--
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