Procházet zdrojové kódy

* Added safesnprintf to strlib.c/h (bugreport:372)

git-svn-id: https://svn.code.sf.net/p/rathena/svn/trunk@11828 54d463be-8e91-2dee-dedb-b68131a5f0ec
FlavioJS před 17 roky
rodič
revize
e207fecd8c
3 změnil soubory, kde provedl 31 přidání a 0 odebrání
  1. 1 0
      Changelog-Trunk.txt
  2. 25 0
      src/common/strlib.c
  3. 5 0
      src/common/strlib.h

+ 1 - 0
Changelog-Trunk.txt

@@ -4,6 +4,7 @@ AS OF SVN REV. 5091, WE ARE NOW USING TRUNK.  ALL UNTESTED BUGFIXES/FEATURES GO
 IF YOU HAVE A WORKING AND TESTED BUGFIX PUT IT INTO STABLE AS WELL AS TRUNK.
 
 2007/11/27
+	* Added safesnprintf to strlib.c/h (bugreport:372) [FlavioJS]
 	* removed login/char server_fd[] arrays, added server[].fd instead
 	* TXT/SQL login server code synchronization [ultramage]
 	- exported several core structures to login.h

+ 25 - 0
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)

+ 5 - 0
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);