tor callgrinds

Watson Ladd watsonbladd at
Sat Feb 17 03:12:20 UTC 2007

Christopher Layne wrote:
> On Fri, Feb 16, 2007 at 09:19:51PM -0500, Watson Ladd wrote:
>> I couldn't help but notice a strncpy in the diagrams. That's
>> inefficient, and insecure. The reason is that strncpy fills the entire
>> rest of the  target string with \x00 but might not do it if the sizes
>> differ. Use strlcpy instead! It's almost a drop in replacement, faster,
>> and more secure.
>> Thanks,
>> Watson Ladd
> Without the visualizer itself it can be difficult to find the context just
> by looking at a snapshot.
> It's mainly being called from _tor_strndup(), from what I can see, which
> specifically notes:
> /** Allocate and return a new string containing the first <b>n</b>
>  * characters of <b>s</b>.  If <b>s</b> is longer than <b>n</b>
>  * characters, only the first <b>n</b> are copied.  The result is
>  * always NUL-terminated.  (Like strndup(s,n), but never returns
>  * NULL.)
>  */
1: So what happens when malloc returns NULL?
2: Won't strlcpy run in time proportional to n? strncpy can't be much
faster as both functions need to loop from 0..n, load the character and
check if its null, and then copy it. The big difference is strncpy keeps
on going.
> char *
> _tor_strndup(const char *s, size_t n DMALLOC_PARAMS)
> {
>   char *dup;
>   tor_assert(s);
>   dup = _tor_malloc((n+1) DMALLOC_FN_ARGS);
>   /* Performance note: Ordinarily we prefer strlcpy to strncpy.  But
>    * this function gets called a whole lot, and platform strncpy is
>    * much faster than strlcpy when strlen(s) is much longer than n.
>    */
>   strncpy(dup, s, n);
>   dup[n]='\0';
>   return dup;
> }
> -cl

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 249 bytes
Desc: OpenPGP digital signature
URL: <>

More information about the tor-dev mailing list