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

Fix potential memory leak in TcpClient::send #2753

Merged
merged 1 commit into from
Apr 8, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 17 additions & 10 deletions Sming/Components/Network/src/Network/TcpClient.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,14 @@ bool TcpClient::send(const char* data, uint16_t len, bool forceCloseAfterSent)
return false;
}

std::unique_ptr<MemoryDataStream> newStream;
auto memoryStream = static_cast<MemoryDataStream*>(stream);
if(memoryStream == nullptr || memoryStream->getStreamType() != eSST_MemoryWritable) {
memoryStream = new MemoryDataStream();
newStream = std::make_unique<MemoryDataStream>();
if(!newStream) {
return false;
}
memoryStream = newStream.get();
}

if(!memoryStream->ensureCapacity(memoryStream->getSize() + len)) {
Expand All @@ -56,11 +61,17 @@ bool TcpClient::send(const char* data, uint16_t len, bool forceCloseAfterSent)

memoryStream->write(data, len);

(void)newStream.release();
return send(memoryStream, forceCloseAfterSent);
}

bool TcpClient::send(IDataSourceStream* source, bool forceCloseAfterSent)
{
std::unique_ptr<IDataSourceStream> sourceRef;
if(stream != source) {
sourceRef.reset(source);
}

if(state != eTCS_Connecting && state != eTCS_Connected) {
return false;
}
Expand All @@ -76,36 +87,32 @@ bool TcpClient::send(IDataSourceStream* source, bool forceCloseAfterSent)
auto chainStream = static_cast<StreamChain*>(stream);
if(!chainStream->attachStream(source)) {
debug_w("Unable to attach source to existing stream chain!");
delete source;
return false;
}
} else {
debug_d("Creating stream chain ...");
auto chainStream = new StreamChain();
if(chainStream == nullptr) {
delete source;
auto chainStream = std::make_unique<StreamChain>();
if(!chainStream) {
debug_w("Unable to create stream chain!");
return false;
}

if(!chainStream->attachStream(stream)) {
delete source;
delete chainStream;
debug_w("Unable to attach stream to new chain!");
return false;
}

if(!chainStream->attachStream(source)) {
delete source;
delete chainStream;
debug_w("Unable to attach source to new chain!");
return false;
}

stream = chainStream;
stream = chainStream.release();
}
}

(void)sourceRef.release();

int length = source->available();
if(length > 0) {
totalSentBytes += length;
Expand Down
Loading