main函数堆栈中的对象在运行第一个任务时(FreeRTOS)被覆盖

问题描述 投票:0回答:2

我试图用一个简单的例子来解释我的问题

typedef function<bool()> TaskCallback;

class Task
{
public:
    Task(TaskCallback task_callback) : task_callback(task_callback)
    {
        long_string_test = "This is a long string 0123456789ABCDEF 0123456789ABCDEF 0123456789ABCDEF";

        xTaskCreate(Task::RunTask, "task_name", 2560, this, 3, &task_handle);
    }

    ~Task()
    {
        while(1); //Breakpoint: The destructor is never called
    }

private:
    static void RunTask(void* params)
    {
        Task* _this = static_cast<Task*>(params);

        _this->task_callback(); //The program crashes here because task_callback doesn't exist
    }

    string long_string_test;

    TaskCallback task_callback;

    TaskHandle_t task_handle;
};

main.cpp

static bool Init_task() { }

void main()
{
    Task task(Init_task);

    vTaskStartScheduler();

    //We should never get here as control is now taken by the FreeRTOS scheduler
    while(1);
}

如果通过long_string_test函数中的调试器检查字符串RunTask的值,我会发现它具有一个奇怪的值,就好像该字符串已被破坏。但是从未调用过Task类的析构函数。

如果我在程序下面更改“ main.cpp”,则该程序可以正常工作,我认为编译器会进行某种优化:

static bool Init_task() { }

Task task(Init_task);

void main()
{
    vTaskStartScheduler();

    //We should never get here as control is now taken by the FreeRTOS scheduler
    while(1);
}

ps.s。显然,编译器优化已禁用

c++ freertos
2个回答
3
投票

1
投票
int* test; static void RunTask(void* params) { Print(*test); //The "test" pointer has a random value } void main() { int temp = 9999; test = &temp; xTaskCreate(RunTask, "task_name", 2560, NULL, 3, NULL); vTaskStartScheduler(); //It seems that FreeRTOS clears the main() stack //We should never get here as control is now taken by the FreeRTOS scheduler while(1); }
© www.soinside.com 2019 - 2024. All rights reserved.