ArduinoCore-API icon indicating copy to clipboard operation
ArduinoCore-API copied to clipboard

HardwareSerial::write(long/int) is incorrect/dangerous!

Open cider101 opened this issue 11 years ago • 3 comments

any value above 255 will just be cut off -

inline size_t write(unsigned long n) { return write((uint8_t)n); }
inline size_t write(long n) { return write((uint8_t)n); }
inline size_t write(unsigned int n) { return write((uint8_t)n); }
inline size_t write(int n) { return write((uint8_t)n); }

please remove or fix the incorrect implementations!

cider101 avatar Mar 09 '14 23:03 cider101

Took me a bit of searching (your bug reports are a bit concise), but I found the code here: https://github.com/arduino/Arduino/blob/master/hardware/arduino/cores/arduino/HardwareSerial.h#L63-L66

The Print class only defines write(uint8_t), but for some reason HardwareSerial also defines write for other types. I'm not so sure why this is needed - I think the compiler will handle type conversion automatically in this case.

In any case, you're misunderstanding the purpose of write(): If you call it with an integer, it will write a single byte with that integer value - it is up to you to make sure the integer is between 0 and 255. If you want to print a full number, then use the print() method instead. If you want to write a bigger number in binary, you'll have to split it up into different bytes manually.

matthijskooijman avatar Mar 10 '14 06:03 matthijskooijman

Thx for your answer. I'll try to be a more verbose in the future. I also fixed the subject of this report with the correct class name.

I fully understand the semantics of write() & print(). The problem here is, that the "long/int" versions of print versions are not just plain wrong but also very hard to find/debug why the numbers are "cut-off". (it' didn't happend to me - just found them by coincidence). Without those overloaded methods, the compiler will give you at least a warning about the "downcast" (or is it an error?). But with those overladed members, everthing seems to work on compile time. Generally, i preferre "syntax-checks" over semantic-checks...meaning everything which can be "forbidden" at compile time should be handled that way...

cider101 avatar Mar 10 '14 07:03 cider101

@sandeepmistry, I'm not sure this really belongs in API. AFAICT from the comments, the Print class is ok, it is just the AVR HardwareSerial class that adds these possibly problematic (and at least unneeded, I think) overloads (maybe other cores too, I did not check).

matthijskooijman avatar Sep 20 '19 15:09 matthijskooijman