Skip to content

SoftwareSerial bug - local variable, dangling pointer #19

Closed
@heX16

Description

I look at this code and see an error (explain in cppreference).
The variable serial is local (in stack), its lifetime is limited to the area of the constructor. After exiting the constructor, the variable serial will be destroyed, and the variable uart will contain dangling pointer. Copying its address should not prolong the lifetime.

I tried looking for some special case that affects the lifetime of a variable and which will not be "undefined behavior" (0, 1, 2, 3, 4, 5, 6 ). But I couldn't find anything suitable for this code...

If my fears are in vain, please give me a link to a description of this case in the standard or explain how it works.

Problem code:

class SerialPM
{
protected:
  Stream *uart;  // hardware/software serial
....

  SerialPM(PMS sensor, uint8_t rx, uint8_t tx) : pms(sensor)
  {
    SoftwareSerial serial(rx, tx);
    uart = &serial;
    hwSerial = false;
  }

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions