提交 3ddf3a59 编写于 作者: D Dave Gamble

stable solution for printing arrays - based on patch donated by Jerome Lang.

Resolves issue in case malloc(0)!=0.



git-svn-id: http://svn.code.sf.net/p/cjson/code@44 e3330c51-1366-4df0-8b21-3ccf24e3d50e
上级 4678f33b
...@@ -327,13 +327,15 @@ static const char *parse_array(cJSON *item,const char *value) ...@@ -327,13 +327,15 @@ static const char *parse_array(cJSON *item,const char *value)
/* Render an array to text */ /* Render an array to text */
static char *print_array(cJSON *item,int depth,int fmt) static char *print_array(cJSON *item,int depth,int fmt)
{ {
char **entries; char **entries=0;
char *out=0,*ptr,*ret;int len=5; char *out=0,*ptr,*ret;int len=5;
cJSON *child=item->child; cJSON *child=item->child;
int numentries=0,i=0,fail=0; int numentries=0,i=0,fail=0;
/* How many entries in the array? */ /* How many entries in the array? */
while (child) numentries++,child=child->next; while (child) numentries++,child=child->next;
if (numentries)
{
/* Allocate an array to hold the values for each */ /* Allocate an array to hold the values for each */
entries=(char**)cJSON_malloc(numentries*sizeof(char*)); entries=(char**)cJSON_malloc(numentries*sizeof(char*));
if (!entries) return 0; if (!entries) return 0;
...@@ -347,6 +349,7 @@ static char *print_array(cJSON *item,int depth,int fmt) ...@@ -347,6 +349,7 @@ static char *print_array(cJSON *item,int depth,int fmt)
if (ret) len+=strlen(ret)+2+(fmt?1:0); else fail=1; if (ret) len+=strlen(ret)+2+(fmt?1:0); else fail=1;
child=child->next; child=child->next;
} }
}
/* If we didn't fail, try to malloc the output string */ /* If we didn't fail, try to malloc the output string */
if (!fail) out=(char*)cJSON_malloc(len); if (!fail) out=(char*)cJSON_malloc(len);
...@@ -357,7 +360,7 @@ static char *print_array(cJSON *item,int depth,int fmt) ...@@ -357,7 +360,7 @@ static char *print_array(cJSON *item,int depth,int fmt)
if (fail) if (fail)
{ {
for (i=0;i<numentries;i++) if (entries[i]) cJSON_free(entries[i]); for (i=0;i<numentries;i++) if (entries[i]) cJSON_free(entries[i]);
cJSON_free(entries); if (entries) cJSON_free(entries);
return 0; return 0;
} }
...@@ -370,7 +373,7 @@ static char *print_array(cJSON *item,int depth,int fmt) ...@@ -370,7 +373,7 @@ static char *print_array(cJSON *item,int depth,int fmt)
if (i!=numentries-1) {*ptr++=',';if(fmt)*ptr++=' ';*ptr=0;} if (i!=numentries-1) {*ptr++=',';if(fmt)*ptr++=' ';*ptr=0;}
cJSON_free(entries[i]); cJSON_free(entries[i]);
} }
cJSON_free(entries); if (entries) cJSON_free(entries);
*ptr++=']';*ptr++=0; *ptr++=']';*ptr++=0;
return out; return out;
} }
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册