Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

重启BUG问题 #4

Open
PXforever opened this issue Apr 13, 2022 · 0 comments
Open

重启BUG问题 #4

PXforever opened this issue Apr 13, 2022 · 0 comments

Comments

@PXforever
Copy link

问题描述

我在使用该项目扩展编程的过程中遇到问题是这样的,初始heap区域(RAM除去.bss与.data)有40KB左右可使用,但是我在继续添加我的代码发现总是重启。

问题原因

跟着代码跑了一遍并使用`system_get_free_heap_size`打印heap,发现有个函数会导致heap区域枯竭,并且随后的字体加载程序会使用`malloc`函数获取内存,且该`malloc`操作不做任何检查空指针,随机使用空指针去赋值,导致控制在操作错误。

代码跟踪路径

SmallDesktopDisplay.cpp->void setup()->getCityWeater()->:
  if (httpCode == HTTP_CODE_OK)
  {
     ....
     weaterData(&jsonCityDZ, &jsonDataSK, &jsonFC);
     ....
  }
weaterData()->clk.loadFont(ZdyLwFont_20)->loadFont("", false);->loadMetrics();->gxAdvance[gNum] =  (uint8_t)readInt32(); // xAdvance - to move x cursor
由于上面代码:gxAdvance =  (uint8_t*)malloc( gFont.gCount );    // xAdvance - to move x cursor
这里并没有申请成功,使得 &gxAdvance  =  NULL。那么就是NULL被赋值,导致错误。

解决

  • 方案一:在系列函数加入空指针检查,检测申请失败与成功
  • 方案二:在追部分代码过程时发现,某些代码中的变量未及时释放,导致内存吃紧,这是我查看代码的过程:
// 获取城市天气
void getCityWeater()
{
	heapa=23920
	
  // String URL = "http://d1.weather.com.cn/dingzhi/" + cityCode + ".html?_="+String(now());//新
  String URL = "http://d1.weather.com.cn/weather_index/" + cityCode + ".html?_=" + String(now()); //原来
  //创建 HTTPClient 对象
  HTTPClient httpClient;
	
	heapa=23808
	
	...............
	
  //如果服务器响应OK则从服务器获取响应体信息并通过串口输出
  if (httpCode == HTTP_CODE_OK)
  {
		heapa=22856
		
    String str = httpClient.getString();	
    int indexStart = str.indexOf("weatherinfo\":");
    int indexEnd = str.indexOf("};var alarmDZ");
		
		heapa=5424

		.....
		
		heapa=4568
    Serial.printf( "heapa size:%u\r\n", system_get_free_heap_size());
    weaterData(&jsonCityDZ, &jsonDataSK, &jsonFC);
    Serial.println("获取成功");
  }
  
	...............
}

可以看到由于str变量获取的网页回应导致大量的heap被占用,且未被释放就进入了下一个高内存消耗的函数weaterData.
这里建议:str.~String();放在weaterData(&jsonCityDZ, &jsonDataSK, &jsonFC);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant