From 523bdcd891fa61dc5a8e1fd077fd1d95389865ec Mon Sep 17 00:00:00 2001 From: "Zhao, Gang" Date: Sun, 15 Aug 2021 21:54:44 +0800 Subject: [PATCH] Fix possible out of bound array access Should check array size before accessing the second to fourth bytes of utf8 as there might be not enough data left in the array. --- algorithms/cpp/UTF8Validation/UTF8Validation.cpp | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/algorithms/cpp/UTF8Validation/UTF8Validation.cpp b/algorithms/cpp/UTF8Validation/UTF8Validation.cpp index 619b8ab63..5b0fe7ac1 100644 --- a/algorithms/cpp/UTF8Validation/UTF8Validation.cpp +++ b/algorithms/cpp/UTF8Validation/UTF8Validation.cpp @@ -67,6 +67,10 @@ class Solution { return false; } + // invalid utf-8 as it doesn't have enough 10xxxxxx + if (i + len > data.size()) { + return false; + } for (int j=i+1; j < i+len; j++) { //checking 10xxxxxx if ( (data[j] & 0xC0) != 0x80 ) { @@ -75,11 +79,6 @@ class Solution { } i += len ; - - if (i > data.size()) { - return false; - } - } return true; }