Create a bunch of objects as demonstration. */
| 41 | |
| 42 | /* Create a bunch of objects as demonstration. */ |
| 43 | static int print_preallocated(cJSON *root) |
| 44 | { |
| 45 | /* declarations */ |
| 46 | char *out = NULL; |
| 47 | char *buf = NULL; |
| 48 | char *buf_fail = NULL; |
| 49 | size_t len = 0; |
| 50 | size_t len_fail = 0; |
| 51 | |
| 52 | /* formatted print */ |
| 53 | out = cJSON_Print(root); |
| 54 | |
| 55 | /* create buffer to succeed */ |
| 56 | /* the extra 5 bytes are because of inaccuracies when reserving memory */ |
| 57 | len = strlen(out) + 5; |
| 58 | buf = (char*)malloc(len); |
| 59 | if (buf == NULL) |
| 60 | { |
| 61 | printf("Failed to allocate memory.\n"); |
| 62 | exit(1); |
| 63 | } |
| 64 | |
| 65 | /* create buffer to fail */ |
| 66 | len_fail = strlen(out); |
| 67 | buf_fail = (char*)malloc(len_fail); |
| 68 | if (buf_fail == NULL) |
| 69 | { |
| 70 | printf("Failed to allocate memory.\n"); |
| 71 | exit(1); |
| 72 | } |
| 73 | |
| 74 | /* Print to buffer */ |
| 75 | if (!cJSON_PrintPreallocated(root, buf, (int)len, 1)) { |
| 76 | printf("cJSON_PrintPreallocated failed!\n"); |
| 77 | if (strcmp(out, buf) != 0) { |
| 78 | printf("cJSON_PrintPreallocated not the same as cJSON_Print!\n"); |
| 79 | printf("cJSON_Print result:\n%s\n", out); |
| 80 | printf("cJSON_PrintPreallocated result:\n%s\n", buf); |
| 81 | } |
| 82 | free(out); |
| 83 | free(buf_fail); |
| 84 | free(buf); |
| 85 | return -1; |
| 86 | } |
| 87 | |
| 88 | /* success */ |
| 89 | printf("%s\n", buf); |
| 90 | |
| 91 | /* force it to fail */ |
| 92 | if (cJSON_PrintPreallocated(root, buf_fail, (int)len_fail, 1)) { |
| 93 | printf("cJSON_PrintPreallocated failed to show error with insufficient memory!\n"); |
| 94 | printf("cJSON_Print result:\n%s\n", out); |
| 95 | printf("cJSON_PrintPreallocated result:\n%s\n", buf_fail); |
| 96 | free(out); |
| 97 | free(buf_fail); |
| 98 | free(buf); |
| 99 | return -1; |
| 100 | } |
no test coverage detected
searching dependent graphs…