jonnieZG/LinkedPointerList

List corruption when inserting to list from both setup() and loop()

Opened this issue · 0 comments

I came across this issue where list gets corrupted, but I'm not sure why. Please see the following Arduino sketch where I basically add a couple of pointers to a global list from setup(), and then a few more from loop(). When I add all members in the same function, either setup() or loop(), there's no issue.

#include <LinkedPointerList.h>

class PinTask {
  public:
  int pin;
  PinTask(int pin) {
    this->pin = pin;
    Serial.print("Added task for pin ");
    Serial.println(pin);
  }
};

LinkedPointerList<PinTask> tasks;

void printTasks() {
  Serial.print("Tasks: ");
  for (int x = 0; x < tasks.size(); x++) {
    PinTask *c = tasks.get(x);
    Serial.print(c->pin);
    Serial.print(" ");
  }
  Serial.println();
}

void setup() {
  Serial.begin(115200);
  // delay otherwise we'll miss some output while
  // the stuff initializes
  while(!Serial);

  PinTask pt1(1);
  tasks.add(&pt1);

  PinTask pt2(2);
  tasks.add(&pt2);

  Serial.println("Init.");
}

bool executed = false;

void loop() {
  if (executed == false) {
    executed = true;

    printTasks();

    PinTask pt3(3);
    tasks.add(&pt3);

    printTasks();

    PinTask pt4(4);
    tasks.add(&pt4);

    printTasks();

    PinTask pt5(5);
    tasks.add(&pt5);

    printTasks();
  }
}

Output - check what happens when task for pin 4 is added:

03:18:10.660 -> Added task for pin 1
03:18:10.660 -> Added task for pin 2
03:18:10.660 -> Init.
03:18:10.660 -> Tasks: 1 2 
03:18:10.660 -> Added task for pin 3
03:18:10.660 -> Tasks: 1 2 3 
03:18:10.660 -> Added task for pin 4
03:18:10.660 -> Tasks: 4 2 3 4   -- should be 1 2 3 4
03:18:10.660 -> Added task for pin 5
03:18:10.660 -> Tasks: 4 5 3 4 5   -- should be 1 2 3 4 5