From 44d1e199db7fc5831801cc145c2e51487ef00adf Mon Sep 17 00:00:00 2001 From: Johan Malm Date: Thu, 7 Nov 2024 21:06:31 +0000 Subject: [PATCH] tests: add buf_add_char() test ...to prove off-by-one test with ASAN. --- t/buf-simple.c | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/t/buf-simple.c b/t/buf-simple.c index 3993ae83..ff22aa10 100644 --- a/t/buf-simple.c +++ b/t/buf-simple.c @@ -69,11 +69,36 @@ test_buf_add_fmt(void **state) buf_reset(&s); } +static void +test_buf_add_char(void **state) +{ + (void)state; + + const char long_string[] = "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"; + size_t len = strlen(long_string); + + /* + * Start off with a long string so that the allocated buffer is only + * just large enough to contain the string and the NULL termination. + */ + struct buf s = BUF_INIT; + buf_add(&s, long_string); + assert_int_equal(s.alloc, len + 1); + + /* Check that buf_add_char() allocates space for the new character */ + buf_add_char(&s, '+'); + assert_true(s.alloc >= (int)len + 2); + assert_string_equal(s.data + s.len - 1, "+"); + + buf_reset(&s); +} + int main(int argc, char **argv) { const struct CMUnitTest tests[] = { cmocka_unit_test(test_expand_title), cmocka_unit_test(test_buf_add_fmt), + cmocka_unit_test(test_buf_add_char), }; return cmocka_run_group_tests(tests, NULL, NULL);