A question...

Conor P. Cahill cpcahil at virtech.UUCP
Thu Aug 17 09:35:20 AEST 1989


In article <1586 at sunset.MATH.UCLA.EDU>, tony at sonia.math.ucla.edu writes:
> 
> 	sprintf (local_str,"%06ld",call_time) ;
> 	strncpy (str_time,local_str,2) ;
> 	strcat  (str_time,":") ;
> 	strncat (str_time,&local_str[2],2) ;
> 	strcat  (str_time,":") ;
> 	strncat (str_time,&local_str[4],2) ;

The problem is that you are doing a strncpy followed by a strcat().  The
strncpy() does not place a null terminator on the target string if the 
source string contains n characters.  Hence the second time through this
code (and all further times) the strcats are applied to the end of 
the string which is then chopped off with:

> 	str_time[8]='\0' ;

This is why the first digit pair is always correct, while the rest of 
the data gets lost.

Solution:
	1. Place a null in str_time[2] after the strncpy().
	2. Change the strncpy()s and strcats()s to a single sprintf as
	   follows:
		sprintf(str_time, "%2s:%2s:%2s" local_str, local_str+2,
						local_str+4);

As a side issue, doing muliple strcat() gets more and more ineffecient because
for each strcat() a full search through each byte of the target string (looking
for a null) is done.

As another side issue,  strncpy() has another effect in that if the source
string is less than n characters, it fills in nulls up to n character positions.



More information about the Comp.lang.c mailing list