diff --git a/icu4c/source/common/unicode/unistr.h b/icu4c/source/common/unicode/unistr.h index a992bf073a..15948627ee 100644 --- a/icu4c/source/common/unicode/unistr.h +++ b/icu4c/source/common/unicode/unistr.h @@ -4162,9 +4162,12 @@ UnicodeString::getTerminatedBuffer() { } else { UChar *array = getArrayStart(); int32_t len = length(); +#ifndef U_VALGRIND if(len < getCapacity() && array[len] == 0) { return array; - } else if(cloneArrayIfNeeded(len+1)) { + } +#endif + if(cloneArrayIfNeeded(len+1)) { array = getArrayStart(); array[len] = 0; return array; diff --git a/icu4c/source/test/intltest/ustrtest.cpp b/icu4c/source/test/intltest/ustrtest.cpp index 77da82737e..3934921627 100644 --- a/icu4c/source/test/intltest/ustrtest.cpp +++ b/icu4c/source/test/intltest/ustrtest.cpp @@ -1090,7 +1090,15 @@ UnicodeStringTest::TestMiscellaneous() test1.setTo(TRUE, u, -1); q=test1.getTerminatedBuffer(); - if(q!=u || test1.length()!=4 || q[3]!=8 || q[4]!=0) { +#ifndef U_VALGRIND + // The VALGRIND option always copies the buffer for getTerminatedBuffer(), + // to avoid reading uninitialized memory when checking for the termination. + if(q!=u) { + errln("UnicodeString(u[-1]).getTerminatedBuffer() returns a bad buffer"); + } +#endif + + if(test1.length()!=4 || q[3]!=8 || q[4]!=0) { errln("UnicodeString(u[-1]).getTerminatedBuffer() returns a bad buffer"); }