Skip to content

Conversation

@aggarg
Copy link
Member

@aggarg aggarg commented Jul 23, 2025

Description

Previously, the shared thread key was deleted in xPortStartScheduler after scheduler was ended. This created a race condition where prvThreadKeyDestructor (responsible for freeing thread-specific heap memory) would not be called if xPortStartScheduler deleted the key before the last task deletion, as destructors are not invoked after key deletion (see https://github.com/walac/glibc/blob/master/nptl/pthread_create.c#L145-L150).

Move thread key deletion to process exit to ensure all thread-specific memory is properly freed.

Test Steps

The LeakSanitzer reports leak without this change for the following program:

#include <FreeRTOS.h>
#include <task.h>

#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>

static StackType_t stack[4096];
static StaticTask_t task;
static TaskHandle_t taskHandle;

static void callback(void *unused)
{
    (void)unused;
    vTaskEndScheduler();
}

int main(void)
{
    taskHandle = xTaskCreateStatic(callback, "thread", 4096, NULL,
                      FREERTOS_PRIORITY_NORMAL, stack, &task);
    vTaskStartScheduler();
    vTaskDelete(taskHandle);
    return 0;
}

Checklist:

  • I have tested my changes. No regression in existing tests.
  • [NA] I have modified and/or added unit-tests to cover the code changes in this Pull Request.

Related Issue

https://forums.freertos.org/t/leaksanitizer-detects-memory-leaks-occasionally-in-gcc-posix/23387

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.

Previously, the shared thread key was deleted in xPortStartScheduler
after scheduler was ended. This created a race condition where
prvThreadKeyDestructor (responsible for freeing thread-specific heap
memory) would not be called if xPortStartScheduler deleted the key
before the last task deletion, as destructors are not invoked after key
deletion (see https://github.com/walac/glibc/blob/master/nptl/pthread_create.c#L145-L150).

Move thread key deletion to process exit to ensure all thread-specific
memory is properly freed.

Signed-off-by: Gaurav Aggarwal <[email protected]>
@aggarg aggarg requested a review from a team as a code owner July 23, 2025 17:43
@sonarqubecloud
Copy link

@aggarg aggarg merged commit 32e5816 into FreeRTOS:main Jul 24, 2025
17 checks passed
@aggarg aggarg deleted the thread_key_deletion branch July 24, 2025 05:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants