Skip to content

Commit

Permalink
Fix memory leak when exception is thrown by impl classes in (#198)
Browse files Browse the repository at this point in the history
Serial::read() vector and string variants.
  • Loading branch information
bsbaliga authored and wjwwood committed Mar 25, 2019
1 parent fba8d81 commit 683e12d
Showing 1 changed file with 18 additions and 2 deletions.
20 changes: 18 additions & 2 deletions src/serial.cc
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,16 @@ Serial::read (std::vector<uint8_t> &buffer, size_t size)
{
ScopedReadLock lock(this->pimpl_);
uint8_t *buffer_ = new uint8_t[size];
size_t bytes_read = this->pimpl_->read (buffer_, size);
size_t bytes_read = 0;

try {
bytes_read = this->pimpl_->read (buffer_, size);
}
catch (const std::exception &e) {
delete[] buffer_;
throw;
}

buffer.insert (buffer.end (), buffer_, buffer_+bytes_read);
delete[] buffer_;
return bytes_read;
Expand All @@ -143,7 +152,14 @@ Serial::read (std::string &buffer, size_t size)
{
ScopedReadLock lock(this->pimpl_);
uint8_t *buffer_ = new uint8_t[size];
size_t bytes_read = this->pimpl_->read (buffer_, size);
size_t bytes_read = 0;
try {
bytes_read = this->pimpl_->read (buffer_, size);
}
catch (const std::exception &e) {
delete[] buffer_;
throw;
}
buffer.append (reinterpret_cast<const char*>(buffer_), bytes_read);
delete[] buffer_;
return bytes_read;
Expand Down

0 comments on commit 683e12d

Please sign in to comment.