【发布时间】:2016-12-21 15:32:49
【问题描述】:
下午好,我正在开始一个新的 Arduino Project 1.6.10 IDE 版本。但是当我使用基于类的结构时遇到了一些内存泄漏问题。
我先发布我的代码,然后我会指出似乎出现内存泄漏的位置。
mainSketchFile.
#include <Ethernet.h>
#include <MemoryFree.h>
#include "Constants.h"
#include "State.h"
StateFactory CurrentStateFactory;
void setup() {
pinMode(BUZZER,OUTPUT);
Serial.begin(9600);
Serial.println("START");
delay(1000);
}
void loop() {
Serial.print(F("Free RAM = "));
Serial.println(freeMemory(), DEC); // print how much RAM is available.
CurrentStateFactory.changeStatus(1);
Serial.println(CurrentStateFactory.getCurrentState()->getNumber());
CurrentStateFactory.changeStatus(2);
Serial.println(CurrentStateFactory.getCurrentState()->getNumber());
}
问题似乎出在 State.hi 我在 cmets 中标记了点
#ifndef State_h
#define State_h
/////////////////// STATE/////////////////////////
class MachineState{
public:
virtual int getNumber();
protected:
};
/////////////////////ACTIVE FULL/////////////////////////////////
class ActiveFull : public MachineState
{
public:
ActiveFull();
virtual int getNumber();
private:
String statusName; //<----- PROBLRM SEEMS TO BE HERE WHEN COMMENTED NO MEMORY LEAK APPEN
int number;
};
ActiveFull::ActiveFull(){
this->number=1;
};
int ActiveFull::getNumber(){
return this->number;
}
////////////////////////////// ACTIVE EMPTY ////////////////////
class ActiveEmpty : public MachineState
{
public:
ActiveEmpty();
virtual int getNumber();
protected:
String statusName;//<----- PROBLRM SEEMS TO BE HERE WHEN COMMENTED NO MEMORY LEAK APPEN
int number;
};
ActiveEmpty::ActiveEmpty(){
this->number=2;
};
int ActiveEmpty::getNumber(){
return this->number;
}
//////////////////FACTORY/////////////////////////////
class StateFactory{
private:
MachineState *currentState;
public:
StateFactory();
void *changeStatus(int choice); // factory
MachineState *getCurrentState();
};
StateFactory::StateFactory(){
MachineState *var1=new ActiveFull();
this->currentState=var1;
}
MachineState *StateFactory::getCurrentState(){
return this->currentState;
}
void *StateFactory::changeStatus(int choice)
{
delete this->currentState; // to prevent memory leak
if (choice == 1){
MachineState *var1=new ActiveFull();
this->currentState=var1;
}
else if (choice == 2){
MachineState *var1=new ActiveEmpty;
this->currentState=var1;
}
else{
MachineState *var1=new ActiveEmpty;
this->currentState=var1;
}
}
#endif
我使用库来跟踪内存使用情况,这是草图的输出:
没有内存泄漏(字符串状态名已注释)
Free RAM = 7897
1
2
Free RAM = 7897
1
2
Free RAM = 7897
1
2
Free RAM = 7897
1
2
Free RAM = 7897
1
2
Free RAM = 7897
1
2
Free RAM = 7897
1
2
Free RAM = 7897
1
2
Free RAM = 7897
1
2
取消注释属性字符串 statusName 时的内存泄漏
Free RAM = 6567
1
2
Free RAM = 6559
1
2
Free RAM = 6551
1
2
Free RAM = 6543
1
2
Free RAM = 6535
1
2
Free RAM = 6527
1
2
感谢您的时间建议。希望你能帮助我。
【问题讨论】:
-
询问操作系统有多少空闲内存可用并不是检测内存泄漏的好方法。原因是操作系统以块的形式提供内存。添加一些成员可能需要另一个块,这将解释您的可用 RAM 数量。
-
name 的 getter 和 setter 在哪里?
-
Gette 和 statusName 的设置者对问题没有影响(我已经测试过了)。我已删除它们以缩短代码,然后将其发布在此处以加快阅读速度。
标签: c++ string memory-leaks arduino class-hierarchy