79585539

Date: 2025-04-22 01:01:42
Score: 0.5
Natty:
Report link

The credit for this answer goes to @dimich. The problem is a copy of the NeoPixel object is being made and since there is none defined in the class, this results in a memory deallocation of the pixels member.

Specifically, the statement pixel = Adafruit_NeoPixel(1, 25, NEO_GRB + NEO_KHZ800); destroys that 1st instance in which pixels is NULL, which is not a problem. It then creates the new one and allocates the memory for the pixels member, and then makes an automatic copy since there is no copy constructor. Since the data member pixels is dynamically allocated, its pointer is copied. In all, three instances are created. The 2nd instance is then destroyed, which causes the problem.

Because the 3rd instance points to the same section of memory for pixels, when the 2nd instance is destroyed, so is the allocation for that memory. Thus, the memory is free for other uses, and the pointer that was copied is no longer valid.

In order to make it clearer:

Adafruit_NeoPixel pixel; // 1st instance; pixels == NULL
pixel = Adafruit_NeoPixel(1, 25, NEO_GRB + NEO_KHZ800); // pixel contains a copy of the pixels pointer, but not its memory.
// pixel.pixels == 0x555 and Adafruit_NeoPixel(1,...).pixels == 0x555
// after the copy is made 0x555 is freed and the pixel.pixels points to freed memory.

From Brave AI, it says it best:

If you do not define a copy constructor, the compiler-generated default copy constructor will copy the data members directly. However, if the class contains pointers or dynamically allocated resources, a custom copy constructor should be defined to handle deep copying, ensuring that the new object has its own copy of the dynamically allocated resources rather than sharing the same resources as the original object.

Thanks again to @dimich for catching this easy to miss problem.

Reasons:
  • Blacklisted phrase (0.5): Thanks
  • Long answer (-1):
  • Has code block (-0.5):
  • User mentioned (1): @dimich
  • User mentioned (0): @dimich
  • Self-answer (0.5):
Posted by: Scott