pinae / AeVOC

Measure particles and aerosoles down to PM2.5 and VOCs and warn if concentrations get too high.
GNU General Public License v3.0
36 stars 9 forks source link

mqtt.cpp subscribeToTopic() memory leak #8

Closed WSchimi closed 2 years ago

WSchimi commented 2 years ago

Hi Pina, sorry for my code reading ;-)

Pointer char* fullTopicStr is only valid in this function and points to allocated memory that is to be released again in this function with free(fullTopicStr).

void subscribeToTopic(const char* topic, void (*callback)(char*)) {
    if (!wifiIsConnected || !mqttClient.connected()) return;
    char* fullTopicStr = createFullTopicStr(topic); // <--- pointer *fullTopicStr is valid only in this function/method
    mqttClient.subscribe(fullTopicStr);
    SubscribedMqttTopic* newTopic = new SubscribedMqttTopic(fullTopicStr, callback);
    SubscribedMqttTopicList* newTopicListElem = new SubscribedMqttTopicList(
        newTopic, subscribedTopicsList);
    subscribedTopicsList = newTopicListElem;
    logger.printf("Subscribed to MQTT-topic: %s\n", fullTopicStr); /* <--- after this line, add */ free(fullTopicStr);
}
WSchimi commented 2 years ago

Hello Pina, Sorry, i didn't see the SubscribedMqttTopic (fullTopicStr, callback) where fullTopicStr is assigned to the private pointer topic and the memory is used for the entire runtime. I close this issue. Best Regards Walter