Skip to content

Commit a9ac410

Browse files
committed
Fix memory leak in copy constructor and copy assignment operator.
1 parent 4be329e commit a9ac410

File tree

1 file changed

+13
-9
lines changed

1 file changed

+13
-9
lines changed

cpp/arduino/Client.h

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
#pragma once
22

3-
#include <Stream.h>
43
#include <IPAddress.h>
4+
#include <Stream.h>
55

66
class Client : public Stream {
77
public:
@@ -11,16 +11,20 @@ class Client : public Stream {
1111
mGodmodeDataIn = new String;
1212
}
1313
}
14-
Client(const Client &client) {
15-
// copy constructor
16-
if (mGodmodeDataIn) {
17-
mGodmodeDataIn = new String(mGodmodeDataIn->c_str());
14+
Client(const Client &client) { // copy constructor
15+
if (this != &client) { // not a self-assignment
16+
if (mGodmodeDataIn) { // replace what we previously had
17+
delete mGodmodeDataIn; // get rid of previous value
18+
mGodmodeDataIn = new String(client.mGodmodeDataIn->c_str());
19+
}
1820
}
1921
}
20-
Client & operator=(const Client &client) {
21-
// copy assignment operator
22-
if (mGodmodeDataIn) {
23-
mGodmodeDataIn = new String(mGodmodeDataIn->c_str());
22+
Client &operator=(const Client &client) { // copy assignment operator
23+
if (this != &client) { // not a self-assignment
24+
if (mGodmodeDataIn) { // replace what we previously had
25+
delete mGodmodeDataIn; // get rid of previous value
26+
mGodmodeDataIn = new String(client.mGodmodeDataIn->c_str());
27+
}
2428
}
2529
return *this;
2630
}

0 commit comments

Comments
 (0)