#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
void overflowTask(void *pvParameters) {
int i = 0;
char tmp[8] = "Overflo";
while (1) {
if (i % 2){
snprintf(tmp, 8, "%s", "Overflo");
}else{
snprintf(tmp, 8, "%s", "Overflow");
}
int len = 8;
char *buffer = malloc(len); // allocate 8 bytes on the heap
if (buffer == NULL) {
printf("Memory allocation failed\n");
break;
}
// Mistake: Copy a string that is larger than the allocated buffer.
strcpy(buffer, tmp); // "Overflow!" is 9 chars + null = 10 bytes, exceeds 8-byte buffer
printf("Buffer contains: %s\n", buffer); // Using memory beyond allocation - undefined behavior
// This buffer overflow can corrupt heap metadata or other variables:contentReference[oaicite:6]{index=6}.
// free(buffer); // normally we would free, but here memory is likely corrupted by overflow.
// Fix: Allocate sufficient space or use safe copying:
// char *buffer = malloc(11); strcpy(buffer, "Overflow!"); // allocate 11 bytes for 10-byte string
i++;
vTaskDelay(pdMS_TO_TICKS(1000));
}
vTaskDelete(NULL);
}
void app_main() {
xTaskCreate(overflowTask, "OverflowTask", 4096, NULL, 1, NULL);
vTaskDelete(NULL);
}