AbidingDude
Programmer
So, the ability to overflow with strcpy() is fairly obvious, and I see how strncpy() isn't the best answer. It won't necessarily null-terminate, and it'll wastefully pad with NULLs. Also, these functions don't offer any kind of error reporting. What about this for a safe string copy? It copies only what's necessary, guarantees null-termination, and when an overflow is detected, returns how many characters past the buffer the source went - albeit a little oddly. It uses the negative portion of the integer range to express how many. The function returns:
positive on success
0 for null pointers for either source or destination
negative for overflow (the absolute value of which is how many bytes over)
positive on success
0 for null pointers for either source or destination
negative for overflow (the absolute value of which is how many bytes over)
C:
#include <string.h>
int strncpy0(char *dst,const char *src,int max)
{
int i;
size_t j;
if(dst==NULL || src==NULL)
return 0;
for(i=0;(dst[i]=src[i])!='\0' && i<max; i++)
;
if(i>=max){
dst[max-1]='\0';
j=strlen(src);
return i-j-1;
}
return i;
}