From 40c4dff74d460624e3de1cc0d49ce6df3ccce613 Mon Sep 17 00:00:00 2001 From: FlavioJS Date: Mon, 20 Apr 2009 17:28:48 +0000 Subject: * Fixed safestrncpy trashing the memory before dst when n == 0. (since r10667, bugreport:2996) git-svn-id: https://rathena.svn.sourceforge.net/svnroot/rathena/trunk@13681 54d463be-8e91-2dee-dedb-b68131a5f0ec --- src/common/strlib.c | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) (limited to 'src/common/strlib.c') diff --git a/src/common/strlib.c b/src/common/strlib.c index 9b97aabba..c1d26622a 100644 --- a/src/common/strlib.c +++ b/src/common/strlib.c @@ -301,14 +301,25 @@ int config_switch(const char* str) return (int)strtol(str, NULL, 0); } -/// always nul-terminates the string +/// strncpy that always nul-terminates the string char* safestrncpy(char* dst, const char* src, size_t n) { - char* ret; - ret = strncpy(dst, src, n); - if( ret != NULL ) - ret[n - 1] = '\0'; - return ret; + if( n > 0 ) + { + char* d = dst; + const char* s = src; + d[--n] = '\0';/* nul-terminate string */ + for( ; n > 0; --n ) + { + if( (*d++ = *s++) == '\0' ) + {/* nul-pad remaining bytes */ + while( --n > 0 ) + *d++ = '\0'; + break; + } + } + } + return dst; } /// doesn't crash on null pointer -- cgit v1.2.3-60-g2f50