Skip to content

Commit

Permalink
heapArray filled version (#2034)
Browse files Browse the repository at this point in the history
For trivial type heapArray returns unitialized memory, which
could be a security issue. Provide a pre-filled version for
trivial types.
  • Loading branch information
mikea committed May 13, 2024
1 parent 4979935 commit e32ad07
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
6 changes: 5 additions & 1 deletion c++/src/kj/array-test.c++
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,11 @@ TEST(Array, TrivialConstructor) {
// EXPECT_NE(chars[1], 0);
// }
}

{
Array<char> chars = heapArray<char>(32, 'x');
for (char c : chars) EXPECT_EQ('x', c);
}
}

TEST(Array, ComplexConstructor) {
Expand All @@ -122,7 +127,6 @@ TEST(Array, ComplexConstructor) {
}
EXPECT_EQ(0, TestObject::count);
}

TEST(Array, ThrowingConstructor) {
TestObject::count = 0;
TestObject::throwAt = 16;
Expand Down
9 changes: 9 additions & 0 deletions c++/src/kj/array.h
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,15 @@ template <typename T, typename Iterator> Array<T> heapArray(Iterator begin, Iter
template <typename T> Array<T> heapArray(std::initializer_list<T> init);
// Allocate a heap array containing a copy of the given content.

template <typename T, typename = EnableIf<KJ_HAS_TRIVIAL_CONSTRUCTOR(T)>>
inline Array<T> heapArray(size_t size, T t) {
// Allocate array pre-filled with t.
// TODO: implement for complex T types without creating `size` instances first.
Array<T> array = heapArray<T>(size);
array.asPtr().fill(t);
return array;
}

template <typename T, typename Container>
Array<T> heapArrayFromIterable(Container&& a) { return heapArray<T>(a.begin(), a.end()); }
template <typename T>
Expand Down

0 comments on commit e32ad07

Please sign in to comment.