alfredapri
alfredapri

Reputation: 3

Parsing longer libcurl responses with cJSON_Parse() sometimes produces broken object

So I'm making a C program using cJSON and curl.

In the curl process itself, I need to send a GET request to an API, and the request link itself would be this.

https://projectkiri.id/api?version=2&mode=findroute&locale=en&start=-6.16935,106.78899&finish=-6.87520,107.60492&presentation=desktop&apikey=C3B9DE7C162B834E

Anyway. The request itself is not problematic, but when I tried performing the request via libcurl and putting it in a write function, as written below...

// struct MemoryStruct {
//     char *memory;
//     size_t size;
// };

size_t write_findroute(void *data, size_t size, size_t nmemb, void *userdata) {
    cJSON *responseJSON;
    cJSON *status;

    size_t realsize = size * nmemb;
    // struct MemoryStruct *mem = (struct MemoryStruct *)userdata;
    // char *ptr = realloc(mem->memory, mem->size + realsize + 1);
    // if(ptr == NULL) {
    //     fprintf(stderr, "Out of memory!\n");
    //     return 0;
    // } 
    // mem->memory = ptr;
    // memcpy(&(mem->memory[mem->size]), data, realsize);
    // mem->size += realsize;
    // mem->memory[mem->size] = 0;

    fprintf(stderr, "%s\n", data); // This is supposed to print the response JSON.
    responseJSON = cJSON_Parse(data);
    fprintf(stderr, "%s\n", cJSON_Print(responseJSON)); // This is also supposed to print the response JSON.

    return realsize;

Here's where it gets finicky.

  1. For some reason, only sometimes, instead of actually printing the response, the cJSON_Print() line out weird string, which are fixed per case. In this case, sometimes instead of the actual response, printing the responseJSON variable will result in "7.60473" instead.
  2. Should I try it with this request (different start parameter value):
    https://projectkiri.id/api?version=2&mode=findroute&locale=en&start=-6.89350,107.60430&finish=-6.87520,107.60492&presentation=desktop&apikey=C3B9DE7C162B834E
    This problem never happens. So it seemed to be fine with smaller-sized responses.
  3. Due to point 2, I had my suspicions that this was caused by insufficient memory, but when I tried implementing the memory checks (the commented codes), the test runs just fine.
  4. What made me even more sure that this wasn't caused by the libcurl itself was the fact that the first response print line (printf("%s\n", data);) always works as intended.

I'm not quite sure what else would be the cause here, since browsing the cJSON issues page didn't bring up anything similar...

Upvotes: 0

Views: 401

Answers (0)

Related Questions