Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prevent segfaults by implementing the rule of three #20

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

ianfixes
Copy link

@ianfixes ianfixes commented Sep 11, 2018

Scope

This change includes the following:

  • when using calloc, don't assume that uint8_t is 1 byte when you can just do sizeof(unit8_t)
  • centralize memory allocation and freeing into standalone functions
  • add a copy constructor and assignment operator to class Adafruit_WS2801 to implement the rule of three [Wikipedia]

There are no functional changes.

Motivation

I'm using arduino_ci to test a library that includes WS2801 as a dependency. I got this strange error:

==49292==ERROR: AddressSanitizer: attempting double-free on 0x603000000280 in thread T0:
    #0 0x10bd62fdd in wrap_free (libclang_rt.asan_osx_dynamic.dylib:x86_64h+0x56fdd)
    #1 0x10bcd5be3 in Adafruit_WS2801::dealloc() Adafruit_WS2801.cpp:84
    #2 0x10bcd6048 in Adafruit_WS2801::~Adafruit_WS2801() Adafruit_WS2801.cpp:132
    #3 0x10bcd6058 in Adafruit_WS2801::~Adafruit_WS2801() Adafruit_WS2801.cpp:131
    #4 0x10bcd3a98 in Strip::~Strip() Strip.h:9
    #5 0x10bcd3a88 in Strip::~Strip() Strip.h:9
    #6 0x10bcd7dfb in test_set_strip_values::task() strip.cpp:31
    #7 0x10bcd9030 in Test::test() ArduinoUnitTests.h:165
    #8 0x10bcd8704 in Test::run(Test::ReporterTAP*) ArduinoUnitTests.h:137
    #9 0x10bcd82a9 in Test::run_and_report(int, char**) ArduinoUnitTests.h:155
    #10 0x10bcd81e8 in main strip.cpp:33
    #11 0x7fff6c6c2014 in start (libdyld.dylib:x86_64+0x1014)

This is caused because the unit test triggers a copy/assignment of the Adafruit_WS2801 class; with no copy constructor explicitly provided, a shallow copy is made, which includes the pixels pointer, meaning that 2 objects are now sharing memory. The trouble happens when the first of those objects drops out of scope and deallocates.

This will probably never happen when run on Arduino, but for unit testing purposes it happens every time.

Testing

Example error from test here https://travis-ci.org/ianfixes/AcceleratedLED/builds/428427957#L185

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant