2

I have this code that crash only in Release:

int main() 
{
  MyStruct s;
  s.field = bla;

  xTaskCreate(TestTask, "TestTask", 2000, &s, 1, 0);

  // other tasks creation
  vTaskStartScheduler();
}


void TestTask(void *p) 
{
  // some delay
  MyStruct* s = (MyStruct*)p;
  another_func(s->field); // hard fault
}

I manage to fix it like this:

int main()
{
  MyStruct* s = new MyStruct();
  s->field = bla;
  xTaskCreate(TestTask, "TestTask", 2000, s, 1, 0);

  // other tasks creation
  vTaskStartScheduler();
}

I don't understand why. Did I fixed it or workaround a memory corruption that can still be there?

Thanks.

Geob-o-matic
  • 5,940
  • 4
  • 35
  • 41
  • Release is set at "-O1" if it helps – Geob-o-matic Jul 04 '18 at 12:39
  • You fix it using `new`? Then tag the question as C++ – David Ranieri Jul 04 '18 at 12:43
  • 1
    If I undertand the documentation corectly then `xTaskCreate` does not block and returns after creating the task. Then `main` is exited and now `MyStruct s;`, which was on the stack of `main` doesn't exist anymore. I also wonder what happens when `main` is exited as normally the program now ends. – Paul Ogilvie Jul 04 '18 at 12:50
  • @PaulOgilvie normally, there is a `vTaskStartScheduler()` function that needs to be called in the main after creating the tasks, not really sure if this is the missing point. – Mike van Dyke Jul 04 '18 at 12:53
  • @PaulOgilvie : I should have mentioned that main does not exist, I've stripped out the code to only show how I'm passing the struct, sorry – Geob-o-matic Jul 04 '18 at 12:53
  • @MikevanDyke: yes exactly, I'll edit my code – Geob-o-matic Jul 04 '18 at 12:54

1 Answers1

3

I'm so stupid, it's written on FreeRTOS' doc: https://www.freertos.org/a00125.html

so it is not valid to pass the address of a stack variable.

Geob-o-matic
  • 5,940
  • 4
  • 35
  • 41