[libcxx] r178544 - Reference: http://lists.cs.uiuc.edu/pipermail/cfe-commits/Week-of-Mon-20130325/077131.html

Howard Hinnant hhinnant at apple.com
Tue Apr 2 08:46:31 PDT 2013


Author: hhinnant
Date: Tue Apr  2 10:46:31 2013
New Revision: 178544

URL: http://llvm.org/viewvc/llvm-project?rev=178544&view=rev
Log:
Reference: http://lists.cs.uiuc.edu/pipermail/cfe-commits/Week-of-Mon-20130325/077131.html

Modified:
    libcxx/trunk/src/support/win32/support.cpp

Modified: libcxx/trunk/src/support/win32/support.cpp
URL: http://llvm.org/viewvc/llvm-project/libcxx/trunk/src/support/win32/support.cpp?rev=178544&r1=178543&r2=178544&view=diff
==============================================================================
--- libcxx/trunk/src/support/win32/support.cpp (original)
+++ libcxx/trunk/src/support/win32/support.cpp Tue Apr  2 10:46:31 2013
@@ -23,14 +23,23 @@ int asprintf(char **sptr, const char *__
     va_end(ap);
     return result;
 }
+
+// Like sprintf, but when return value >= 0 it returns a pointer to a malloc'd string in *sptr.
+// If return >= 0, use free to delete *sptr.
 int vasprintf( char **sptr, const char *__restrict fmt, va_list ap )
 {
     *sptr = NULL;
-    int count = vsnprintf( *sptr, 0, fmt, ap );
-    if( (count >= 0) && ((*sptr = (char*)malloc(count+1)) != NULL) )
-    {
-        vsprintf( *sptr, fmt, ap );
-        sptr[count] = '\0';
+    int count = vsnprintf( NULL, 0, fmt, ap ); // Query the buffer size required.
+    if( count >= 0 ) {
+        char* p = static_cast<char*>(malloc(count+1)); // Allocate memory for it and the terminator.
+        if ( p == NULL )
+            return -1;
+        if ( vsnprintf( p, count+1, fmt, ap ) == count ) // We should have used exactly what was required.
+            *sptr = p;
+        else { // Otherwise something is wrong, likely a bug in vsnprintf. If so free the memory and report the error.
+            free(p);
+            return -1;
+        }
     }
 
     return count;





More information about the cfe-commits mailing list