Skip to content

Commit aa0304a

Browse files
committedMar 4, 2024
[string] Return 0 if nullptr is passed to StringLength
This commit ensures that segfault won't happen if `nullptr` is passed to `StringLength()`. Signed-off-by: Maciej Baczmanski <maciej.baczmanski@nordicsemi.no>
1 parent 41526d5 commit aa0304a

File tree

2 files changed

+7
-4
lines changed

2 files changed

+7
-4
lines changed
 

‎src/core/common/string.cpp

+5-2
Original file line numberDiff line numberDiff line change
@@ -89,13 +89,16 @@ MatchType Match(const char *aString, const char *aPrefixString, StringMatchMode
8989

9090
uint16_t StringLength(const char *aString, uint16_t aMaxLength)
9191
{
92-
uint16_t ret;
92+
uint16_t ret = 0;
9393

94-
for (ret = 0; (ret < aMaxLength) && (aString[ret] != kNullChar); ret++)
94+
VerifyOrExit(aString != nullptr);
95+
96+
for (; (ret < aMaxLength) && (aString[ret] != kNullChar); ret++)
9597
{
9698
// Empty loop.
9799
}
98100

101+
exit:
99102
return ret;
100103
}
101104

‎src/core/common/string.hpp

+2-2
Original file line numberDiff line numberDiff line change
@@ -85,8 +85,8 @@ static constexpr char kNullChar = '\0'; ///< null character.
8585
* @param[in] aString A pointer to the string.
8686
* @param[in] aMaxLength The maximum length in bytes.
8787
*
88-
* @returns The number of characters that precede the terminating null character or @p aMaxLength, whichever is
89-
* smaller.
88+
* @returns The number of characters that precede the terminating null character or @p aMaxLength,
89+
* whichever is smaller. `0` if @p aString is `nullptr`.
9090
*
9191
*/
9292
uint16_t StringLength(const char *aString, uint16_t aMaxLength);

0 commit comments

Comments
 (0)