Add bounds check in get_ptr.
authorNick Terrell <terrelln@fb.com>
Tue, 21 Jul 2015 18:34:55 +0000 (11:34 -0700)
committerfacebook-github-bot-4 <folly-bot@fb.com>
Tue, 21 Jul 2015 23:52:50 +0000 (16:52 -0700)
Summary: `get_ptr()` checks if the index is past the end of the array, but it
doesn't check if it is less than 0, while `at()` does.

Reviewed By: @yfeldblum

Differential Revision: D2258548

folly/dynamic.cpp
folly/test/DynamicTest.cpp

index 840c5f336ab7b180db51a484a738d49e466bc80a..e58292447f27b0bcc916b404b57a1de73c75200b 100644 (file)
@@ -165,7 +165,7 @@ const dynamic* dynamic::get_ptr(dynamic const& idx) const {
     if (!idx.isInt()) {
       throw TypeError("int64", idx.type());
     }
-    if (idx >= parray->size()) {
+    if (idx < 0 || idx >= parray->size()) {
       return nullptr;
     }
     return &(*parray)[idx.asInt()];
index e471d021fce8d9387c42731089e7d54acf6035dd..184d57f451e442f4d335d0c824f7470e32048b3a 100644 (file)
@@ -269,6 +269,7 @@ TEST(Dynamic, ObjectForwarding) {
 TEST(Dynamic, GetPtr) {
   dynamic array = { 1, 2, "three" };
   EXPECT_TRUE(array.get_ptr(0));
+  EXPECT_FALSE(array.get_ptr(-1));
   EXPECT_FALSE(array.get_ptr(3));
   EXPECT_EQ(dynamic("three"), *array.get_ptr(2));
   const dynamic& carray = array;