简体   繁体   English

C ++数组/指针泄漏内存

[英]C++ array/pointer leak memory


When I run function handleRequestWithParams(..) few times I am run out of RAM memory on my microcontroller (ESP8266). 几次运行handleRequestWithParams(..)函数时,我的微控制器(ESP8266)的RAM内存不足。
I am not sure that I should delete "paramsNames", "paramsValues" and maybe "values", or maybe I should create this arrays in other way? 我不确定是否应该删除“ paramsNames”,“ paramsValues”以及“ values”,或者是否应该以其他方式创建此数组?

struct RequestStructure {
    int paramsCount;
    String* paramsNames;
};

void Requests::handleRequestWithParams(RequestStructure requestStructure) {
    const int PARAMS_COUNT = requestStructure.paramsCount;

    String* paramsNames = requestStructure.paramsNames;
    String* paramsValues = readParamsValues(paramsNames, PARAMS_COUNT);

    _server.send(200, TYPE_TEXT, response(paramsNames[0], paramsValues[0]);

    //delete paramsNames;
    //delete paramsValues;
}

String* Requests::readParamsValues(String* paramsNames, int count) {
    String* values = new String[count];
    for (int i = 0; i < count; i++) {
        values[i] = server.arg(paramsNames[i].c_str());
    }
    return values;
}

Every piece of memory you acquire with new or new T[] must be deleted using delete or delete[] accordingly. 您必须使用deletedelete[]相应地删除使用newnew T[]获取的每条内存。

Otherwise you are leaking memory. 否则,您将泄漏内存。


That said, I'd strongly discourage to deal with new / delete yourself. 就是说,我强烈不鼓励您处理new / delete自己的事情。
Use either std::vector , or the classes from Dynamic memory management of the c++ standard library instead. 请使用std::vector或c ++标准库的动态内存管理中的类。

These provide clear semantics how ownership of dynamic storage will be transferred between the distributed pieces of your code workflow, and manage the deletion automatically if the reference ceases to exist. 这些提供了清晰的语义,说明如何在代码工作流的分布式部分之间转移动态存储的所有权,并在引用不存在时自动管理删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM