Hello,
I am using the NRF52832 processor on a custom board to collect data from a sensor and send it to a mobile app using BLE and NUS service in JSON format. However, after a few minutes, the transmission stops due to memory allocation failure.
Here is a piece of my code:
root_G_P_R=cJSON_CreateObject();
cJSON_AddItemToObject(root_G_P_R, "info", info_G_P_R=cJSON_CreateObject());
cJSON *plan_date = cJSON_CreateArray();
for (int i= 0 ; i<APP_PlanCounter+1;i++)
{
cJSON_AddItemToArray(plan_date, cJSON_CreateNumber(APP_PlanDate[i]));
}
cJSON *TR = cJSON_CreateArray();
for (int i= 0 ; i<APP_PlanCounter+1;i++)
{
cJSON_AddItemToArray(TR, cJSON_CreateNumber(APP_TRS[i]));
}
cJSON *TRCR = cJSON_CreateArray();
for (int i= 0 ; i<APP_PlanCounter+1;i++)
{
cJSON_AddItemToArray(TRCR, cJSON_CreateNumber(App_TRCS[i]));
}
cJSON_AddItemToObject(root_G_P_R, "key", cJSON_CreateString("G_P_R"));
cJSON_AddItemToObject(info_G_P_R, "tr", TR);
cJSON_AddItemToObject(info_G_P_R, "trac", TRCR);
cJSON_AddNumberToObject(info_G_P_R, "plan", plan);
cJSON_AddNumberToObject(info_G_P_R, "PT", App_PT[APP_PlanCounter]);
cJSON_AddItemToObject(info_G_P_R, "date", plan_date);
if (print_preallocated(root_G_P_R) != 0) {
cJSON_Delete(root_G_P_R);
exit(EXIT_FAILURE);
}
cJSON_Delete(root_G_P_R);
and in the case of print_preallocated:
static int print_preallocated(cJSON *root)
{
char *out = NULL;
char *buf = NULL;
char *buf_fail = NULL;
uint16_t len = 0;
size_t len_fail = 0;
out = cJSON_Print(root);
len = strlen(out) + 5;
buf = (char*)malloc(len);
if (buf == NULL)
{
printf("Failed to allocate memory.\n");
exit(1);
}
len_fail = strlen(out);
buf_fail = (char*)malloc(len_fail);
if (buf_fail == NULL)
{
printf("Failed to allocate memory.\n");
exit(1);
}
ble_nus_data_send(&m_nus, (uint8_t *)out , &len, m_conn_handle);
free(out);
free(buf_fail);
free(buf);
return 0;
}
I have read in a thread that applying cJSON_Init() to the main would be helpful, but when I added this function, the JSON parse data process failed:
cJSON_Parse(received_data) --> cJSON_ParseWithOpts --> cJSON_New_Item --> cJSON_malloc
I suspect that there is something wrong with memory allocation. Could you please help me with this problem? Is there any configuration or consideration that I should have taken but missed out on?
Thank you for your assistance.