Fix ESP32 MQTT Memory Leak
Budget: $15 – $25 USD
I'm looking for expert on memory leaks with MQTT on an ESP32 to refactor the code to prevent memory allocation errors.
Freelancer must have platformIO, an ESP32-S3, and an MCU to communicate with the ESP32-S3 via I2C.
Candidates must answer this interview question. Why does the following code have a JSON parse error with free(msgBuffer), but not without?
// Helper to push JSON into send queue
void queueIotMsgToPublish(String jsonPayload) {
if (sendQueueHandle != NULL) {
char *msgBuffer = (char *)malloc(jsonPayload.length() + 1);
if (msgBuffer) {
strcpy(msgBuffer, jsonPayload.c_str());
if (xQueueSendToBack(sendQueueHandle, &msgBuffer, 1000*portTICK_PERIOD_MS) == pdPASS) {
// Serial.println("IOT: Queued msg to publish");
} else {
Serial.println("IOT: ERROR publish queue full");
}
}
// free(msgBuffer);
}
}
// MQTT Receive Task
void processMqttMsgFromQueueTask(void *parameter) {
char *msgPayload = NULL;
for (;;) {
if (xQueueReceive(recvQueueHandle, &msgPayload, 10*portTICK_PERIOD_MS) == pdTRUE) {
if (msgPayload) {
String msgStr = String(msgPayload);
uint32_t length = strlen(msgPayload);
// Serial.printf("IOT: Rx length %d \r\n", length);
Serial.printf("IOT: Rx %s \r\n", msgStr.c_str());
JsonDocument msgJson;
i2cCommPacketStruct MsgPacket;
DeserializationError err = deserializeJson(msgJson, msgPayload);
if (!err) {
// Process Message from IotCore
} else {
Serial.print("IOT: JSON parse error: ");
Serial.println(err.c_str());
Serial.println(msgPayload);
}
}
}
vTaskDelay(2);
}
}
Freelancer must have platformIO, an ESP32-S3, and an MCU to communicate with the ESP32-S3 via I2C.
Candidates must answer this interview question. Why does the following code have a JSON parse error with free(msgBuffer), but not without?
// Helper to push JSON into send queue
void queueIotMsgToPublish(String jsonPayload) {
if (sendQueueHandle != NULL) {
char *msgBuffer = (char *)malloc(jsonPayload.length() + 1);
if (msgBuffer) {
strcpy(msgBuffer, jsonPayload.c_str());
if (xQueueSendToBack(sendQueueHandle, &msgBuffer, 1000*portTICK_PERIOD_MS) == pdPASS) {
// Serial.println("IOT: Queued msg to publish");
} else {
Serial.println("IOT: ERROR publish queue full");
}
}
// free(msgBuffer);
}
}
// MQTT Receive Task
void processMqttMsgFromQueueTask(void *parameter) {
char *msgPayload = NULL;
for (;;) {
if (xQueueReceive(recvQueueHandle, &msgPayload, 10*portTICK_PERIOD_MS) == pdTRUE) {
if (msgPayload) {
String msgStr = String(msgPayload);
uint32_t length = strlen(msgPayload);
// Serial.printf("IOT: Rx length %d \r\n", length);
Serial.printf("IOT: Rx %s \r\n", msgStr.c_str());
JsonDocument msgJson;
i2cCommPacketStruct MsgPacket;
DeserializationError err = deserializeJson(msgJson, msgPayload);
if (!err) {
// Process Message from IotCore
} else {
Serial.print("IOT: JSON parse error: ");
Serial.println(err.c_str());
Serial.println(msgPayload);
}
}
}
vTaskDelay(2);
}
}