Skip to content
This repository has been archived by the owner on Jul 24, 2022. It is now read-only.

Commit

Permalink
chore(printf): cleanup secure strlen() function, added test cases
Browse files Browse the repository at this point in the history
  • Loading branch information
mpaland committed Dec 5, 2018
1 parent 4b60eb6 commit d46b3d2
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 6 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ Therefore I decided to write an own, final implementation which meets the follow
- Support of decimal/floating number representation (with an own fast itoa/ftoa)
- Reentrant and thread-safe, malloc free, no static vars/buffers
- LINT and compiler L4 warning free, mature, coverity clean, automotive ready
- Extensive test suite (> 340 test cases) passing
- Extensive test suite (> 350 test cases) passing
- Simply the best *printf* around the net
- MIT license

Expand Down
9 changes: 4 additions & 5 deletions printf.c
Original file line number Diff line number Diff line change
Expand Up @@ -139,14 +139,13 @@ static inline void _out_fct(char character, void* buffer, size_t idx, size_t max
}


// internal strlen
// internal secure strlen
// \return The length of the string (excluding the terminating 0)
// limited by 'max' size if non-zero
static inline unsigned int _strlen(const char* str, size_t max)
static inline unsigned int _strnlen_s(const char* str, size_t maxsize)
{
const char* s;
size_t n = max;
for (s = str; *s && (max?n--:1); ++s);
for (s = str; *s && maxsize--; ++s);
return (unsigned int)(s - str);
}

Expand Down Expand Up @@ -649,7 +648,7 @@ static int _vsnprintf(out_fct_type out, char* buffer, const size_t maxlen, const

case 's' : {
char* p = va_arg(va, char*);
unsigned int l = _strlen(p, precision);
unsigned int l = _strnlen_s(p, precision ? precision : (size_t)-1);
// pre padding
if (flags & FLAGS_PRECISION) {
l = (l < precision ? l : precision);
Expand Down
26 changes: 26 additions & 0 deletions test/test_suite.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1187,6 +1187,32 @@ TEST_CASE("unknown flag", "[]" ) {
}


TEST_CASE("string length", "[]" ) {
char buffer[100];

test::sprintf(buffer, "%.4s", "This is a test");
REQUIRE(!strcmp(buffer, "This"));

test::sprintf(buffer, "%.4s", "test");
REQUIRE(!strcmp(buffer, "test"));

test::sprintf(buffer, "%.7s", "123");
REQUIRE(!strcmp(buffer, "123"));

test::sprintf(buffer, "%.7s", "");
REQUIRE(!strcmp(buffer, ""));

test::sprintf(buffer, "%.4s%.2s", "123456", "abcdef");
REQUIRE(!strcmp(buffer, "1234ab"));

test::sprintf(buffer, "%.4.2s", "123456");
REQUIRE(!strcmp(buffer, ".2s"));

test::sprintf(buffer, "%.*s", 3, "123456");
REQUIRE(!strcmp(buffer, "123"));
}


TEST_CASE("buffer length", "[]" ) {
char buffer[100];
int ret;
Expand Down

0 comments on commit d46b3d2

Please sign in to comment.