1
0
mirror of https://gitlab.com/80486DX2-66/gists synced 2024-12-27 05:40:17 +05:30
gists/c-programming/strings/asprintf.c

67 lines
1.6 KiB
C
Raw Normal View History

2024-01-25 23:03:58 +05:30
/*
* asprintf.c
*
* Author: Intel A80486DX2-66
2024-04-26 01:46:39 +05:30
* License: Unlicense
2024-01-25 23:03:58 +05:30
*/
2024-01-15 22:12:17 +05:30
#include "asprintf.h"
ssize_t asprintf(char** strp, char* format, ...) {
va_list args;
va_start(args, format);
ssize_t result = (ssize_t) vsnprintf(NULL, 0, format, args);
if (result < 0) {
2024-01-15 22:12:17 +05:30
va_end(args);
return -1;
}
size_t size = (size_t) result + 1;
*strp = malloc(size * sizeof(char));
2024-01-15 22:12:17 +05:30
if (*strp == NULL) {
va_end(args);
return -1;
}
result = (ssize_t) vsnprintf(*strp, size, format, args);
2024-01-15 22:12:17 +05:30
va_end(args);
if (result < 0) {
free(*strp);
return -1;
}
return result;
}
2024-01-28 18:16:26 +05:30
#ifdef TEST
# include <inttypes.h>
# include <math.h>
# include <stdbool.h>
# 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)
2024-01-28 18:16:26 +05:30
int main(void) {
2024-03-14 01:10:19 +05:30
const char* world = ", World";
2024-01-28 18:16:26 +05:30
char* output;
ssize_t result = asprintf(&output, "Hello%s! -- Unsigned 32-bit type is "
2024-01-28 18:16:26 +05:30
"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("no segmentation fault", true);
PRINT_ASSERT("no errors occurred", result != -1);
2024-01-28 18:16:26 +05:30
PRINT_ASSERT("zero termination test", output[result] == '\0');
printf("[asprintf (%zu)] '%s'\n", result, output);
return 0;
}
#endif