diff options
author | FlavioJS <FlavioJS@54d463be-8e91-2dee-dedb-b68131a5f0ec> | 2007-11-27 23:06:37 +0000 |
---|---|---|
committer | FlavioJS <FlavioJS@54d463be-8e91-2dee-dedb-b68131a5f0ec> | 2007-11-27 23:06:37 +0000 |
commit | 8515d1011cc7dcbbd4db1b80af5496559f3cec87 (patch) | |
tree | 0be48b44f4e39269323cd25ba85725946debaad9 /src/common | |
parent | 72c6ebad02446c7bf3b416c98e17c8ddd0a8671a (diff) | |
download | hercules-8515d1011cc7dcbbd4db1b80af5496559f3cec87.tar.gz hercules-8515d1011cc7dcbbd4db1b80af5496559f3cec87.tar.bz2 hercules-8515d1011cc7dcbbd4db1b80af5496559f3cec87.tar.xz hercules-8515d1011cc7dcbbd4db1b80af5496559f3cec87.zip |
* Added safesnprintf to strlib.c/h (bugreport:372)
git-svn-id: https://rathena.svn.sourceforge.net/svnroot/rathena/trunk@11828 54d463be-8e91-2dee-dedb-b68131a5f0ec
Diffstat (limited to 'src/common')
-rw-r--r-- | src/common/strlib.c | 25 | ||||
-rw-r--r-- | src/common/strlib.h | 5 |
2 files changed, 30 insertions, 0 deletions
diff --git a/src/common/strlib.c b/src/common/strlib.c index d0b312f0a..db47c969b 100644 --- a/src/common/strlib.c +++ b/src/common/strlib.c @@ -316,6 +316,31 @@ size_t safestrnlen(const char* string, size_t maxlen) return ( string != NULL ) ? strnlen(string, maxlen) : 0; } +/// Works like snprintf, but always nul-terminates the buffer. +/// Returns the size of the string (without nul-terminator) +/// or -1 if the buffer is too small. +/// +/// @param buf Target buffer +/// @param sz Size of the buffer (including nul-terminator) +/// @param fmt Format string +/// @param ... Format arguments +/// @return The size of the string or -1 if the buffer is too small +int safesnprintf(char* buf, size_t sz, const char* fmt, ...) +{ + va_list ap; + int ret; + + va_start(ap,fmt); + ret = vsnprintf(buf, sz, fmt, ap); + va_end(ap); + if( ret < 0 || (size_t)ret >= sz ) + {// overflow + buf[sz-1] = '\0';// always nul-terminate + return -1; + } + return ret; +} + /// Returns the line of the target position in the string. /// Lines start at 1. int strline(const char* str, size_t pos) diff --git a/src/common/strlib.h b/src/common/strlib.h index 4df5a51d2..31e364e2a 100644 --- a/src/common/strlib.h +++ b/src/common/strlib.h @@ -37,6 +37,11 @@ char* safestrncpy(char* dst, const char* src, size_t n); /// doesn't crash on null pointer size_t safestrnlen(const char* string, size_t maxlen); +/// Works like snprintf, but always nul-terminates the buffer. +/// Returns the size of the string (without nul-terminator) +/// or -1 if the buffer is too small. +int safesnprintf(char* buf, size_t sz, const char* fmt, ...); + /// Returns the line of the target position in the string. /// Lines start at 1. int strline(const char* str, size_t pos); |