[Asterisk-Dev] [RFC] strncpy -> ast_copy_string

Kevin P. Fleming kpfleming at digium.com
Mon May 2 08:53:46 MST 2005


Ledion B wrote:

> Can we see the code for your test_copy_string and
> test_strncpy.

Attached.

>>From my understanding of the documentation of strncpy,
> the padding will only happen if n > strlen(src), which
> makes sense. If you make sure than n !> strlen(src),
> then no padding happens.

n will _always_ be greater than strlen(src), at least 99.99% of the 
cases. We are copying strings into fixed-size buffers that always have 
enough room. There is no way to make sure that "n !> strlen(src)", that 
would require dynamically sized buffers, in which case there would be no 
need for strncpy at all.
-------------- next part --------------
#include <string.h>

void eater(const char *str)
{
  return;
}

int main()
{
  char target[80];
  int x;

  for (x = 1; x < 10000000; x++) {
    strncpy(target, "12345678901234567890", sizeof(target) - 1);
    eater(target);
  }
}
-------------- next part --------------
static void ast_copy_string(char *dst, const char *src, int size)
{
	while (*src && size--)
		*dst++ = *src++;
	if (__builtin_expect(!size, 0))
		dst--;
	*dst = '\0';
}

static void eater(const char *str)
{
  return;
}

int main()
{
  char target[80];
  int x;

  for (x = 1; x < 10000000; x++) {
    ast_copy_string(target, "12345678901234567890", sizeof(target) - 1);
    eater(target);
  }
}


More information about the asterisk-dev mailing list