#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "esp_system.h" // for esp_get_free_heap_size()
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
void leakTask(void *pvParameters) {
size_t start_heap = esp_get_free_heap_size();
printf("Start free heap: %ul bytes\n", start_heap);
int iteration = 0;
while (1) {
char *buffer = malloc(100); // allocate 100 bytes each iteration
if (buffer == NULL) {
printf("Failed to allocate memory!\n");
break; // exit loop on allocation failure (out of memory)
}
// Use the allocated memory
sprintf(buffer, "Iteration %d: Hello world!", iteration++);
printf("%s\n", buffer);
// Forgot to free 'buffer' -> memory leak each loop iteration
// free(buffer); // **Fix:** free the allocated memory to avoid leak
if (iteration % 10 == 0) { // every 10 iterations, report free heap
printf("Free heap after %d iterations: %ul bytes\n",
iteration, esp_get_free_heap_size());
}
vTaskDelay(pdMS_TO_TICKS(500)); // delay 500ms between iterations
}
vTaskDelete(NULL);
}
void app_main() {
xTaskCreate(leakTask, "LeakTask", 4096, NULL, 1, NULL);
// The LeakTask will run indefinitely (or until memory runs out).
// No other tasks are created in this example.
vTaskDelete(NULL); // delete app_main task, LeakTask continues
}