c - C 代码中的内存问题或 Arduino 限制?

标签 c json rest memory arduino

我正在开发一个使用 Arduino Yùn 模块的项目。我目前正在尝试从 Arduino 创建 JSON 以返回。此 JSON 的创建发生在嵌套的 for 循环中。我正在使用 aJson Arduino 库 ( https://github.com/interactive-matter/aJson )。

当我构建 Arduino 时,它第一次就被正确发送。当我之后执行 REST 调用时,我只得到一个空行 \r\n (这很可能是 HTTP 响应 header 之后的空行)...

我不确定我是否正在处理这里的内存问题,或者是否存在任何其他问题。我非常习惯使用面向目标的语言,我知道 C,但由于它没有垃圾收集释放内存,所以我不太清楚......

这是我创建和发送 JSON 的方法的代码:

void getAll(YunClient client) {
    aJsonObject *root, *object;
    root = aJson.createArray();

    int i = 0;    
    for(i; i < 4; i++) {
        int j = 0;
        for(j; j < 3; j++) {   
          aJson.addItemToArray(root, object = aJson.createObject());
          aJson.addNumberToObject(object, "test", 1);
          //should I do a free(object); here?
      }
    }       

  //headers
  //client.println("HTTP/1.1 200 OK");
  client.println("Status: 200");
  client.println("Content-Type: application/javascript");
  client.println("Access-Control-Allow-Origin: *");
  //client.print("\r\n");
  client.println();

  // Send feedback to client
  char* result = aJson.print(root);
  Serial.println(result);
  client.println(result);

  free(root);
  free(result);  
}

如您所见,在嵌套的 for 循环内,我不确定是否应该释放那里的内存。

当我第一次进行 REST 调用时,我收到以下消息: enter image description here

我第二次得到这个(但我的Arduino没有卡住/崩溃,其他功能继续工作,它仍然发送数据,它似乎是空的......): enter image description here

最佳答案

我不会使用free对于 aJson 结构! 你怎么知道这些结构中有什么?检查库文档以了解如何免费。

我在您链接的页面上找到了这个:

Finished? Delete the root (this takes care of everything else).

aJson.deleteItem(root);

还有这个(因为您使用的是 aJson 列表):

Lists are easily handled in aJson, to create a list you can simply use the provided API functions:

aJson.create<TYPE>Array(objects,24);

You simply pass a array of the respective type: char*[], int[] and so on.

aJSON doesn't make any assumptions about what order you create things in. You can attach the objects, as above, and later add children to each of those objects with

aJson.addItemToArray()

or remove them with

aJson.deleteItemFromArray() - which also deletes the objects, or aJson.detachItemFromArray() - which does not free the memory

As soon as you call aJson.print(), it renders the structure to text.

关于c - C 代码中的内存问题或 Arduino 限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27473479/

相关文章:

c - 不允许使用不完整类型,2 个结构

c - 如何让 strtok() 返回十进制数而不是整数?

c - 循环循环,但仍然难以理解

javascript - 将逗号分隔的字符串下载为 csv

java - 如何使用 REST API 在 Jira 中创建问题?

c - mallocing 是否等同于具有指定数组大小的指针

javascript - 使用 NodeJS 将 JSON 插入 MySQL JSON 列格式

xml - JSON 是像 XML 一样的标记语言吗?

java - WADL 生成工具

javascript - QueryReadStore 将 JSON 加载到 DataGrid 中,但 JsonRestStore 不会(来自同一来源)