vibraphone / cjson-bson

cJSON with support for BSON serialization
MIT License
1 stars 1 forks source link

printf warning about wrong format #4

Closed UnePierre closed 9 years ago

UnePierre commented 9 years ago

Hi! Nice implementation.

Problem

My build issues a warning about a mismatch in printf()-Arguments:

cJSON_BSON.c:393:5: warning: format ‘%lu’ expects argument of type ‘long unsigned int’, but argument 4 has type ‘ptrdiff_t’ [-Wformat=]

Fix 1

That can be remedied by an explicit cast, as shown by the following patch:

diff --git a/cJSON_BSON.c b/cJSON_BSON.c
index d92ab40..352dabb 100644
--- a/cJSON_BSON.c
+++ b/cJSON_BSON.c
@@ -390,7 +390,7 @@ size_t bson_item_name(cJSON* item, char* buf, size_t bufsize, ptrdiff_t* idxName
   size_t result = 0;
   if (idxName)
     {
-    result = snprintf(buf, bufsize, "%lu", *idxName);
+    result = snprintf(buf, bufsize, "%lu", (long unsigned)(*idxName));
     if (result > bufsize)
       result = bufsize - 1; /* Prevent overruns */
     (*idxName) ++; /* increment the index for the next item. */

Fix 2

My preferred solution would be to #include <inttypes.h> and use "%" PRIuPTR instead of "%lu".

--- a/cJSON_BSON.c
+++ b/cJSON_BSON.c
@@ -30,6 +30,7 @@
 #include <stdlib.h>
 #include <float.h>
 #include <limits.h>
+#include <inttypes.h>
 #include <ctype.h>
 #include "cJSON.h"
 #include "cJSON_BSON.h"
@@ -390,7 +391,7 @@ size_t bson_item_name(cJSON* item, char* buf, size_t bufsize, ptrdiff_t* idxName
   size_t result = 0;
   if (idxName)
     {
-    result = snprintf(buf, bufsize, "%lu", *idxName);
+    result = snprintf(buf, bufsize, "%" PRIuPTR, *idxName);
     if (result > bufsize)
       result = bufsize - 1; /* Prevent overruns */
     (*idxName) ++; /* increment the index for the next item. */

Thanks, Max

vibraphone commented 9 years ago

Thanks for the report; I will try to fix in the next day or so. I agree that Fix 2 is preferable.