@@ -99,11 +99,12 @@ int BLERemoteCharacteristic::writeValue(const uint8_t value[], int length, bool
9999 length = maxLength;
100100 }
101101
102- _value = (uint8_t *)realloc (_value, length);
103- if (_value == NULL ) {
104- // realloc failed
102+ uint8_t * newValue = (uint8_t *)realloc (_value, length);
103+ if (newValue == NULL ) {
104+ // realloc failed - keep old buffer to avoid memory leak
105105 return 0 ;
106106 }
107+ _value = newValue;
107108
108109 if ((_properties & BLEWrite) && withResponse) {
109110 uint8_t resp[4 ];
@@ -180,14 +181,16 @@ bool BLERemoteCharacteristic::read()
180181 return false ;
181182 }
182183
183- _valueLength = respLength - 1 ;
184- _value = (uint8_t *)realloc (_value, _valueLength );
184+ int newLength = respLength - 1 ;
185+ uint8_t * newValue = (uint8_t *)realloc (_value, newLength );
185186
186- if (_value == NULL ) {
187- _valueLength = 0 ;
187+ if (newValue == NULL ) {
188+ // realloc failed - keep old buffer to avoid memory leak
188189 return false ;
189190 }
190191
192+ _value = newValue;
193+ _valueLength = newLength;
191194 memcpy (_value, &resp[1 ], _valueLength);
192195
193196 return true ;
@@ -246,18 +249,23 @@ void BLERemoteCharacteristic::addDescriptor(BLERemoteDescriptor* descriptor)
246249
247250void BLERemoteCharacteristic::writeValue (BLEDevice device, const uint8_t value[], int length)
248251{
249- _valueLength = length;
250- _value = (uint8_t *)realloc (_value, _valueLength);
251-
252- if (_value == NULL ) {
253- _valueLength = 0 ;
254- return ;
252+ uint8_t * newValue = (uint8_t *)realloc (_value, length);
253+
254+ if (newValue == NULL ) {
255+ // realloc failed, but still signal that an update occurred
256+ // so the user knows data arrived (even though we couldn't store it)
257+ _valueUpdated = true ;
258+ _updatedValueRead = false ;
259+ // keep old _value and _valueLength intact to avoid memory leak
260+ // and preserve previous data
261+ } else {
262+ _value = newValue;
263+ _valueLength = length;
264+ _valueUpdated = true ;
265+ _updatedValueRead = false ;
266+ memcpy (_value, value, _valueLength);
255267 }
256268
257- _valueUpdated = true ;
258- _updatedValueRead = false ;
259- memcpy (_value, value, _valueLength);
260-
261269 if (_valueUpdatedEventHandler) {
262270 _valueUpdatedEventHandler (device, BLECharacteristic (this ));
263271 }
0 commit comments