在 STM32 移植 cJSON 库后,使用 cJSON_Parse(),解析失败。
char cmd[512] = "{\"msg\":\"this is successful start up\",\"result\":1,\"action\":\"req_startUp\",\"responseData\":\"trustedDevice\",\"serial_no\":\"0341\",\"timestamp\":1656489886238}";
cJSON *pRoot = cJSON_Parse(cmd);
const char *error_ptr = cJSON_GetErrorPtr();
if (error_ptr != NULL)
{
printf("Error before: %s\n", error_ptr);
}
使用 cJSON_GetErrorPtr() 分析出以下错误:
Error before: ,"timestamp":1656489886238}
而当去掉 serial_no 字段后,则能够解析成功。
char cmd[512] = "{\"msg\":\"this is successful start up\",\"result\":1,\"action\":\"req_startUp\",\"responseData\":\"trustedDevice\",\"timestamp\":1656489886238}";
当解析的的数据比较长时,会解析失败,但是短的数据则没有问题,后面排查是因为 cJSON 解析需要用到的内存比较大,溢出导致解析失败。
查看 STM32 启动文件。如 startup_stm32f407xx.s,发现:

**注意:**记得要 cJSON_Delete 删除对象,还有 cJSON_Print 会一直不停申请内存,所有调用完之后一定要 free 释放,否则多次调用后一样会内存溢出。导致后面的 cJSON_Print 会申请不到内存。
增大空间后,问题解决

• 由 Leung 写于 2022 年 6 月 30 日