Browse Source

Correctly handle zero-length buffers.

tags/v0.9.3
Michael Brown 18 years ago
parent
commit
efd6281a35
1 changed files with 9 additions and 10 deletions
  1. 9
    10
      src/core/vsprintf.c

+ 9
- 10
src/core/vsprintf.c View File

171
  * @v args		Arguments corresponding to the format string
171
  * @v args		Arguments corresponding to the format string
172
  * @ret len		Length of formatted string
172
  * @ret len		Length of formatted string
173
  */
173
  */
174
-int vcprintf ( struct printf_context *ctx, const char *fmt, va_list args ) {
174
+size_t vcprintf ( struct printf_context *ctx, const char *fmt, va_list args ) {
175
 	int flags;
175
 	int flags;
176
 	int width;
176
 	int width;
177
 	uint8_t *length;
177
 	uint8_t *length;
296
  */
296
  */
297
 int vsnprintf ( char *buf, size_t size, const char *fmt, va_list args ) {
297
 int vsnprintf ( char *buf, size_t size, const char *fmt, va_list args ) {
298
 	struct printf_context ctx;
298
 	struct printf_context ctx;
299
-	int len;
300
-
301
-	/* Ensure last byte is NUL if a size is specified.  This
302
-	 * catches the case of the buffer being too small, in which
303
-	 * case a trailing NUL would not otherwise be added.
304
-	 */
305
-	if ( size != PRINTF_NO_LENGTH )
306
-		buf[size-1] = '\0';
299
+	size_t len;
300
+	size_t end;
307
 
301
 
308
 	/* Hand off to vcprintf */
302
 	/* Hand off to vcprintf */
309
 	ctx.handler = printf_sputc;
303
 	ctx.handler = printf_sputc;
312
 	len = vcprintf ( &ctx, fmt, args );
306
 	len = vcprintf ( &ctx, fmt, args );
313
 
307
 
314
 	/* Add trailing NUL */
308
 	/* Add trailing NUL */
315
-	printf_sputc ( &ctx, '\0' );
309
+	if ( size ) {
310
+		end = size - 1;
311
+		if ( len < end )
312
+			end = len;
313
+		buf[end] = '\0';
314
+	}
316
 
315
 
317
 	return len;
316
 	return len;
318
 }
317
 }

Loading…
Cancel
Save