Search

Sponsored Links

Meta

Categories

Archives

Recent Posts

RSS Feeds

04
Dec

Safe String Copy(strcpy) and Concatenate(strcat) Operations

Related Blog Items

I’d covered bad standard APIs in my previous article, here I’ve attempted to overcome those defects in standard APIs, please check these fucntions.. I’ll post more functions later..

Strcpy:
1)copy src to string dst of size size
2)At most size-1 characters will be copied
3)Returns strlen(src); if retval >= size, truncation occurred
4)Always NUL terminates (unless size is 0)

size_t safe_strcpy(char *dst, const char *src, size_t size)
{
  const char *s = src;
  size_t n = size;

  if (size != 0)
  {
    while (--size != 0)
    {
      if ((*dst++ = *src++) == 0)
      break;
    }
  }

  if (size == 0)
  {
    if (n)
      *dst = 0;
    while (*src++);
  }

  //count does not include ''
  return(src-s-1);
}

strcat:
1)Appends src to string dst of size size, unlike strncat size is the full size of dst
2)At most size-1 characters will be copied
3)Always NUL terminates (unless size = siz, truncation occurred.

size_t safe_strcat(char *dst, const char *src, size_t size)
{
  char *d = dst;
  const char *s = src;
  size_t n = size;
  size_t dstlen;
 
  while (n-- != 0 && *d != 0)
  {
    d++;
  }
 
  dstlen = d - dst;
  n = size - dstlen;
 
  if (n == 0)
  {
    return(dstlen + strlen(s));
  }
 
  while (*s != 0)
  {
    if (n != 1)
    {
      *d++ = *s;
      n--;
    }
    s++;
  }
  *d = 0;
 
  return(dstlen + (s - src));
}

download src safe string operations

Popularity: 8%

You need to log on to convert this article into PDF


Related Blog Items

No Comments

No comments yet.

Leave a comment

*
To prove you're a person (not a spam script), type the security word shown in the picture.
Anti-spam image