Pantek Library
Hosting Provided By
CybrHost
High Speed Hosting

Re: strncpy() and NULL termination

From: Dan Cross <tenser(at)spitfire.ecsel.psu.edu>
Date: Sun Feb 16 1997 - 21:51:04 EST


> > (strncpy(3) only returns NULL or a valid pointer, but there is
> > no indication of truncation at all, unless you check to see if
> > buf[len - 1] != '\0'.)
>
> If you do that then you need to set buf[len-1] = '\0' before the strncpy.

Eh? Why would you need to do that? strncpy(3) does nul padding... ;-)

> So, anyone up for doing a standard routine for logging (syslog?) when a

That's not a bad idea. btw, would folks find something like this useful?

char *
sstrtncpy(dst, src, len)

	char	*dst;
	const	char *src;
	size_t	len;
{
	register size_t	last;

	if (len != 0)
	{
		(void)strncpy(dst, src, len);
		last = len - 1;

		if (dst[last] != '\0')
		{
			dst[last] = '\0';
			return(NULL);
		}
	}

	return(dst);

}

The idea here is to check for truncation by looking at the last character in dst to see if it is non-nul. If that's true, then the string was truncated,  so nul-terminate it and use the return as NULL to indicate this. If not, then the string was NOT truncated. The point is that the return value can now be used as an indication of truncation, and action can be taken accordingly.   The register variable for ``last'' is an attempt at an optimization,  but wether or not this really GETS you anything is debatable.

Of course, all the usual caveats regarding standards compliance (or rather, lack thereof) apply.

  • Dan C.
Received on Sun Feb 16 18:51:56 1997

This archive was generated by hypermail 2.1.8 : Wed Aug 23 2006 - 12:41:02 EDT

Do you need help?X

Contact Us  Legal Notices  Order Services Online 
Pantek Home  Privacy Policy  IT news  Site Map  Pantek Library