Skip to content

Commit 99896d8

Browse files
Kyle ChisholmFSMaxB
authored andcommitted
function to print and compare to preallocated buffer
1 parent 4d1dcaa commit 99896d8

1 file changed

Lines changed: 57 additions & 0 deletions

File tree

‎test.c‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,63 @@ struct record
8282
const char *country;
8383
};
8484

85+
86+
/* Create a bunch of objects as demonstration. */
87+
int print_preallocated(cJSON *root)
88+
{
89+
/* declarations */
90+
char *out = NULL;
91+
char *buf = NULL;
92+
char *buf_fail = NULL;
93+
int len = 0;
94+
int len_fail = 0;
95+
96+
/* formatted print */
97+
out = cJSON_Print(root);
98+
99+
/* create buffer to succeed */
100+
/* the extra 64 bytes are in case a floating point value is printed */
101+
len = strlen(out) + 64;
102+
buf = malloc(len);
103+
104+
/* create buffer to fail */
105+
len_fail = strlen(out);
106+
buf_fail = malloc(len_fail);
107+
108+
/* Print to buffer */
109+
if (cJSON_PrintPreallocated(root, buf, len, 1) != 0) {
110+
printf("cJSON_PrintPreallocated failed!\n");
111+
if (strcmp(out, buf) != 0) {
112+
printf("cJSON_PrintPreallocated not the same as cJSON_Print!\n");
113+
printf("cJSON_Print result:\n%s\n", out);
114+
printf("cJSON_PrintPreallocated result:\n%s\n", buf);
115+
}
116+
free(out);
117+
free(buf_fail);
118+
free(buf);
119+
return -1;
120+
}
121+
122+
/* success */
123+
printf("%s\n", buf);
124+
125+
/* force it to fail */
126+
if (cJSON_PrintPreallocated(root, buf_fail, len_fail, 1) == 0) {
127+
printf("cJSON_PrintPreallocated failed to show error with insufficient memory!\n");
128+
printf("cJSON_Print result:\n%s\n", out);
129+
printf("cJSON_PrintPreallocated result:\n%s\n", buf_fail);
130+
free(out);
131+
free(buf_fail);
132+
free(buf);
133+
return -1;
134+
}
135+
136+
free(out);
137+
free(buf_fail);
138+
free(buf);
139+
return 0;
140+
}
141+
85142
/* Create a bunch of objects as demonstration. */
86143
void create_objects(void)
87144
{

0 commit comments

Comments
 (0)