From 1ec1b4a9e790f9aaa35728f71901705a3d363c34 Mon Sep 17 00:00:00 2001 From: Intel A80486DX2-66 Date: Sun, 28 Jan 2024 15:46:26 +0300 Subject: [PATCH] C: add test for asprintf.c --- c-programming/asprintf.c | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/c-programming/asprintf.c b/c-programming/asprintf.c index cdb6363..26b488c 100644 --- a/c-programming/asprintf.c +++ b/c-programming/asprintf.c @@ -34,3 +34,33 @@ ssize_t asprintf(char** strp, char* format, ...) { return result; } + +#ifdef TEST +# include +# include +# include +# define PRINT_ASSERT(caption, test) do { \ + bool test_result = (test); \ + printf("[test] " caption ": %s\n", test_result ? "OK" : "failed"); \ + if (test_result == false) \ + exit(EXIT_FAILURE); \ +} while (0); + +int main(void) { + const char* world = " world"; + + char* output; + size_t result = asprintf(&output, "Hello%s! -- Unsigned 32-bit type is " + "constrained to lie\nwithin the range of integer values from " + "%" PRIu32 " to %" PRIu32 " inclusive.", world, 0, + (uint32_t) (powf(2.0f, 32.0f) - 1.0f)); + + PRINT_ASSERT("segmentation fault", true); + PRINT_ASSERT("no errors", errno == 0); + PRINT_ASSERT("zero termination test", output[result] == '\0'); + + printf("[asprintf (%zu)] '%s'\n", result, output); + + return 0; +} +#endif