Skip to content

Commit 475edde

Browse files
gmossessianinsolor
authored andcommitted
avoid memory overflow on corrupted file
1 parent ac04dd3 commit 475edde

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

lib/dawgdic/dictionary.h

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -49,10 +49,22 @@ class Dictionary {
4949
}
5050

5151
SizeType size = static_cast<SizeType>(base_size);
52-
std::vector<DictionaryUnit> units_buf(size);
53-
if (!input->read(reinterpret_cast<char *>(&units_buf[0]),
54-
sizeof(DictionaryUnit) * size)) {
55-
return false;
52+
std::vector<DictionaryUnit> units_buf;
53+
54+
// read the file in batches to avoid a corrupted file from asking to allocate
55+
// a very large amount of memory
56+
SizeType batch_size = 1000;
57+
while( size > 0 ) {
58+
SizeType size_to_read = std::min(size, batch_size);
59+
SizeType cur_size = units_buf.size();
60+
units_buf.resize(cur_size + size_to_read);
61+
if (!input->read(reinterpret_cast<char *>(&units_buf[cur_size]),
62+
sizeof(DictionaryUnit) * size_to_read)) {
63+
return false;
64+
}
65+
// subtract size_to_read (not batch_size)
66+
// so size does not integer overflow on becoming negative
67+
size -= size_to_read;
5668
}
5769

5870
SwapUnitsBuf(&units_buf);

0 commit comments

Comments
 (0)