Fix possible leak in String

Fixes: https://github.com/espressif/arduino-esp32/issues/710
This commit is contained in:
me-no-dev 2017-10-12 06:52:35 +03:00
parent f1e87d91be
commit 0fa25c09ef

View File

@ -23,6 +23,7 @@
#include "WString.h" #include "WString.h"
#include "stdlib_noniso.h" #include "stdlib_noniso.h"
#include "esp32-hal-log.h"
//extern "C" { //extern "C" {
//#include "esp_common.h" //#include "esp_common.h"
//} //}
@ -165,19 +166,23 @@ unsigned char String::reserve(unsigned int size)
unsigned char String::changeBuffer(unsigned int maxStrLen) unsigned char String::changeBuffer(unsigned int maxStrLen)
{ {
size_t newSize = (maxStrLen + 16) & (~0xf); size_t newSize = ((maxStrLen + 16) & (~0xf)) - 1;
char *newbuffer = (char *) malloc(newSize); char *newbuffer = (char *) realloc(buffer, newSize+1);
if(newbuffer) { if(newbuffer) {
memset(newbuffer, 0, newSize); if(newSize > len){
memcpy(newbuffer, buffer, len); if(newSize > capacity){
if (buffer) { memset(newbuffer+capacity, 0, newSize-capacity);
free(buffer); }
} else {
//new buffer can not fit the old len
newbuffer[newSize] = 0;
len = newSize;
} }
capacity = newSize - 1; capacity = newSize;
buffer = newbuffer; buffer = newbuffer;
return 1; return 1;
} }
buffer = newbuffer; log_e("realloc failed! Buffer unchanged");
return 0; return 0;
} }