1 /* sdump.c -- library to allocate and format a printable version of a
2 * string with embedded NUL */
5 * \author Matthias Andree
8 * This file is available under the GNU Lesser General Public License
9 * v2.1 or any later version of the GNU LGPL.
12 #include <ctype.h> /* for isprint() */
13 #include <stdio.h> /* for sprintf() */
14 #include <stdlib.h> /* for size_t */
15 #include "xmalloc.h" /* for xmalloc() */
17 #include "sdump.h" /* for prototype */
19 /** sdump converts a byte string \a in of size \a len into a printable
20 * string and returns a pointer to the memory region.
21 * \returns a pointer to a xmalloc()ed string that the caller must
22 * free() after use. This function causes program abort on failure
23 * through xmalloc. xmalloc is a function that calls malloc() and aborts
24 * the program if malloc() returned NULL i. e. failure. */
25 char *sdump(const char *in, size_t len)
30 for (i = 0; i < len; i++) {
31 outlen += isprint((unsigned char)in[i]) ? 1 : 4;
34 oi = out = (char *)xmalloc(outlen + 1);
35 for (i = 0; i < len; i++) {
36 if (isprint((unsigned char)in[i])) {
39 oi += sprintf(oi, "\\x%02X", (unsigned char)in[i]);