Skip to content

Commit 944c570

Browse files
authored
fix: handle reallocation failure gracefully in DataPointer::resize() (#37)
1 parent 630ee8b commit 944c570

2 files changed

Lines changed: 13 additions & 2 deletions

File tree

include/ncrypto.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -690,6 +690,8 @@ class DataPointer final {
690690
bool isSecure() const { return secure_; }
691691

692692
private:
693+
void free();
694+
693695
void* data_ = nullptr;
694696
size_t len_ = 0;
695697
bool secure_ = false;

src/ncrypto.cpp

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -228,14 +228,18 @@ void DataPointer::zero() {
228228
OPENSSL_cleanse(data_, len_);
229229
}
230230

231-
void DataPointer::reset(void* data, size_t length) {
231+
void DataPointer::free() {
232232
if (data_ != nullptr) {
233233
if (secure_) {
234234
OPENSSL_secure_clear_free(data_, len_);
235235
} else {
236236
OPENSSL_clear_free(data_, len_);
237237
}
238238
}
239+
}
240+
241+
void DataPointer::reset(void* data, size_t length) {
242+
free();
239243
data_ = data;
240244
len_ = length;
241245
}
@@ -258,7 +262,12 @@ DataPointer DataPointer::resize(size_t len) {
258262
size_t actual_len = std::min(len_, len);
259263
auto buf = release();
260264
if (actual_len == len_) return DataPointer(buf.data, actual_len);
261-
buf.data = OPENSSL_realloc(buf.data, actual_len);
265+
auto new_data = OPENSSL_realloc(buf.data, actual_len);
266+
if (new_data == nullptr) {
267+
free();
268+
return {};
269+
}
270+
buf.data = new_data;
262271
buf.len = actual_len;
263272
return DataPointer(buf);
264273
}

0 commit comments

Comments
 (0)