I followed the instructions of this post: Storing an array of function pointers. To show my problem I shorted my code extremely but the problem is still there.

My classes are defined as followes:

class MyBaseClass
  MyBaseClass(String functionName);
  String functionName();
  String _functionName;

class MyDerivedClassA : public MyBaseClass
  MyDerivedClassA(String functionName);

class MyDerivedClassB : public MyBaseClass
  MyDerivedClassB(String functionName);

MyBaseClass::MyBaseClass(String functionName) {
  _functionName = functionName;

String MyBaseClass::functionName(){
  return _functionName;

MyDerivedClassA::MyDerivedClassA(String functionName) : MyBaseClass(functionName) {}

MyDerivedClassB::MyDerivedClassB(String functionName) : MyBaseClass(functionName) {}

The test method is this:

void test(){
  MyBaseClass *_elements[1000];
  int _elementCount = 0;

  for (int i = 0; i < 2; i++){
    if (i == 0){
      MyDerivedClassA tmp("MyDerivedClassA");

      _elements[_elementCount] = (MyBaseClass *)&tmp;
      Serial.println( _elements[_elementCount]->functionName() );

    } else if (i == 1){
      MyDerivedClassB tmp("MyDerivedClassB");

      _elements[_elementCount] = (MyBaseClass *)&tmp;
      Serial.println( _elements[_elementCount]->functionName() );


    Serial.println( _elements[_elementCount]->functionName() );


  Serial.println("count: " + String(_elementCount));
  for (int i = 0; i < _elementCount; i++) {
    Serial.println("loop: " + String(i));
    Serial.println( _elements[i]->functionName() );

When the code is running I get the following at the serial monitor:



count: 2
loop: 0

loop: 1

I dont understand, why the first call of "_elements[_elementCount]->functionName()" inside the first loop returns the correct value and the second only an empty string. Inside the second loop it again returns an empty string. I think it's the same problem like inside the first loop.

And there is the problem, that my NodeMCU crashes if the code is executed.

This is the output while it carshes:

Soft WDT reset

ctx: cont 
sp: 3ffffd20 end: 3fffffd0 offset: 01b0


 ets Jan  8 2013,rst cause:2, boot mode:(1,7)

 ets Jan  8 2013,rst cause:4, boot mode:(1,7)

wdt reset

Where is my problem?

  • 1
    You allocate 1000 pointers, aka 1000*4 Bytes on the stack. That kills the thread. (MyBaseClass *_elements[1000];) – Maximilian Gerhardt Sep 13 '18 at 21:16
  • ok, this was a really stupid mistake... Setting "MyBaseClass *_elements[10];" solved the crash problem. But the output at the serial monitor is still the same... – vocaris Sep 13 '18 at 21:40
  • 2
    Your tmp variable doesn't survive the { } it is placed in. It is de-allocated when it exits the }. Move the temp variables to an outer, greater scope or new and delete them. – Maximilian Gerhardt Sep 13 '18 at 21:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.