Skip to content

Commit d7f20e3

Browse files
committed
Bugfix: reference counting was accessing freed memory
1 parent b39ac7e commit d7f20e3

File tree

4 files changed

+21
-14
lines changed

4 files changed

+21
-14
lines changed

src/local/BLELocalAttribute.cpp

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,10 @@
1919

2020
#include "BLELocalAttribute.h"
2121

22+
std::map<BLELocalAttribute*,int> BLELocalAttribute::_refCount;
23+
2224
BLELocalAttribute::BLELocalAttribute(const char* uuid) :
23-
_uuid(uuid),
24-
_refCount(0)
25+
_uuid(uuid)
2526
{
2627
}
2728

@@ -51,14 +52,15 @@ enum BLEAttributeType BLELocalAttribute::type() const
5152

5253
int BLELocalAttribute::retain()
5354
{
54-
_refCount++;
55+
_refCount[this]++;
5556

56-
return _refCount;
57+
return _refCount[this];
5758
}
5859

5960
int BLELocalAttribute::release()
6061
{
61-
_refCount--;
62+
_refCount[this]--;
63+
if (_refCount[this] == 0) _refCount.erase(this);
6264

63-
return _refCount;
65+
return _refCount[this];
6466
}

src/local/BLELocalAttribute.h

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@
2222

2323
#include "utility/BLEUuid.h"
2424

25+
#include <map>
26+
2527
#define BLE_ATTRIBUTE_TYPE_SIZE 2
2628

2729
enum BLEAttributeType {
@@ -54,7 +56,7 @@ class BLELocalAttribute
5456

5557
private:
5658
BLEUuid _uuid;
57-
int _refCount;
59+
static std::map<BLELocalAttribute*,int> _refCount;
5860
};
5961

6062
#endif

src/remote/BLERemoteAttribute.cpp

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,10 @@
2121

2222
#include "BLERemoteAttribute.h"
2323

24+
std::map<BLERemoteAttribute*,int> BLERemoteAttribute::_refCount;
25+
2426
BLERemoteAttribute::BLERemoteAttribute(const uint8_t uuid[], uint8_t uuidLen) :
25-
_uuid(BLEUuid::uuidToString(uuid, uuidLen)),
26-
_refCount(0)
27+
_uuid(BLEUuid::uuidToString(uuid, uuidLen))
2728
{
2829
}
2930

@@ -38,14 +39,15 @@ const char* BLERemoteAttribute::uuid() const
3839

3940
int BLERemoteAttribute::retain()
4041
{
41-
_refCount++;
42+
_refCount[this]++;
4243

43-
return _refCount;
44+
return _refCount[this];
4445
}
4546

4647
int BLERemoteAttribute::release()
4748
{
48-
_refCount--;
49+
_refCount[this]--;
50+
if (_refCount[this] == 0) _refCount.erase(this);
4951

50-
return _refCount;
52+
return _refCount[this];
5153
}

src/remote/BLERemoteAttribute.h

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
#define _BLE_REMOTE_ATTRIBUTE_H_
2222

2323
#include <Arduino.h>
24+
#include <map>
2425

2526
class BLERemoteAttribute
2627
{
@@ -35,7 +36,7 @@ class BLERemoteAttribute
3536

3637
private:
3738
String _uuid;
38-
int _refCount;
39+
static std::map<BLERemoteAttribute*,int> _refCount;
3940
};
4041

4142
#endif

0 commit comments

Comments
 (0)