Skip to content

Commit

Permalink
avoid memory overflow on corrupted file
Browse files Browse the repository at this point in the history
  • Loading branch information
gmossessian authored and insolor committed Nov 4, 2023
1 parent ac04dd3 commit 475edde
Showing 1 changed file with 16 additions and 4 deletions.
20 changes: 16 additions & 4 deletions lib/dawgdic/dictionary.h
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,22 @@ class Dictionary {
}

SizeType size = static_cast<SizeType>(base_size);
std::vector<DictionaryUnit> units_buf(size);
if (!input->read(reinterpret_cast<char *>(&units_buf[0]),
sizeof(DictionaryUnit) * size)) {
return false;
std::vector<DictionaryUnit> units_buf;

// read the file in batches to avoid a corrupted file from asking to allocate
// a very large amount of memory
SizeType batch_size = 1000;
while( size > 0 ) {
SizeType size_to_read = std::min(size, batch_size);
SizeType cur_size = units_buf.size();
units_buf.resize(cur_size + size_to_read);
if (!input->read(reinterpret_cast<char *>(&units_buf[cur_size]),
sizeof(DictionaryUnit) * size_to_read)) {
return false;
}
// subtract size_to_read (not batch_size)
// so size does not integer overflow on becoming negative
size -= size_to_read;
}

SwapUnitsBuf(&units_buf);
Expand Down

0 comments on commit 475edde

Please sign in to comment.