Web Development Blog

24K Design Studio :: Blog :: A safe string copy function to handle char*
Author:
Password:
A safe string copy function to handle char*
01:34, 05 Mar, 2011
by David

strcpy is not safe as it cannot limit the number of characters to be copied. strcpy_s is safe, but it cannot deal with char*. After searching for a while, I think I need a safe string copy function to handle char* and here it is:

// Initial dstRemainChar should be sizeof(dst)-1. And manually pending '\0' is needed.
size_t str_copy(char* dst, size_t& dstRemainChar, char* src) {
 char c = *src;
 size_t copied = 0;
 while (c != '\0') {
  if (!dstRemainChar) {
   break;
  }
  *dst = c;
  dst++;
  src++;
  dstRemainChar--;
  copied++;
  c = *src;
 }
 return copied;
}

 

An example of use:

char dst[80];
strcpy_s<80>(dst, "First ");
// Here strcpy_s<74>(dst + 6, "Second"); cannot compile!
size_t dstRemainChar = 80 - 1 - 6;
char *pdst = dst + 6;
pdst += str_copy(pdst, dstRemainChar, "Second ");
pdst += str_copy(pdst, dstRemainChar, "Third");
pdst[0] = 0;
cout << "Line: " << dst << endl;cout << "Remained Character: " << dstRemainChar << endl;
Tags: C C++
Reply:
Your name:
Only visible to the author.

Tell us you are not a robot. What is captcha1captchaOcaptcha2 =

Reply
#1
rvbeabmo
05:03, 25 Nov, 2015
 
1
Reply
Your name:
Only visible to the author.

Tell us you are not a robot. What is captcha1captchaOcaptcha2 =

Reply
View the latest 5 entries.