Hi there!
So I was writing a network connected program for air quality measurements using Arduino and at some point I had to allocate for a string a char*
. As I have learned, I tried to free()
and then set it to NULL
, so I do not run out of dynamic memory or leave dangling pointers (although I am not sure I have to do the latter as the pointer itself is created in a function and is not static, but that is the lesser problem here, still answers are welcome regarding that as well).
I get the following error message:
CORRUPT HEAP: Bad tail at 0x3ffd7a7e. Expected 0xbaad5678 got 0xbaad5600
assert failed: multi_heap_free multi_heap_poisoning.c:253 (head != NULL)
This is the part of my code related to it:
StaticJsonDocument<128> telemetry_msg;
telemetry_msg["msgCount"] = telemetry_send_count;
serializeJson(telemetry_msg, serialized_telemetry_msg);
// TODO: Refactor and extract to function.
/* Telemetry message resizing magic. */
heap_caps_check_integrity_all(true);
uint8_t size = 0;
while (serialized_telemetry_msg[size] != NULL_TERMINATOR)
{
size++;
}
char* optimized_telemetry_msg = (char*)malloc(sizeof(char) * size);
for (uint8_t i = 0; i <= size; i++)
{
optimized_telemetry_msg[i] = serialized_telemetry_msg[i];
}
LogInfo("Optimized msg: " + String(optimized_telemetry_msg) + "\n");
/* Telemetry message resizing magic. */
result = esp_mqtt_client_publish(
mqtt_client,
telemetry_topic,
optimized_telemetry_msg,
size,
CONFIG_MQTT_CLIENT_QOS,
CONFIG_MQTT_CLIENT_MESSAGE_RETAIN_POLICY);
// FIXME: CORRUPUT HEAP: assert failed: multi_heap_free multi_heap_poisoning.c:253 (head != NULL)
free(optimized_telemetry_msg);
optimized_telemetry_msg = NULL;
When I am not using a the free()
call, this CORRUPT HEAP problem doesn't show up.
I am suspecting that the esp_mqtt_client_publish
might be the problem here as the argument optimized_telemetry_msg
is supposed to be a const char*
... But I am not sure.
I am pretty sure that the problem is not that I run out of memory as if I do not call free, the program can run for a pretty long time, actually I do not even think that I have ran into any problems related to that...