Program for converting an array of bytes to hexadecimal I have written a program that outputs the hexadecimal representation of an array of bytes. The program works just fine, and I am confident (thanks to valgrind) that I don't have any memory leaks. However, I am not so confident I am doing this the simplest, nor most readable way. It seems to me I have written a lot of code for a small task.

I am looking for general feedback, including code style, types, variable naming, usage of malloc, and simpler ways of appending a char array to a string, possibly avoiding sprintf.

The program was written to exercise storing a hexadecimal representation of a byte array in a string, not printing it out directly using printf().

#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;string.h&gt;

int main() {
    const unsigned char bytearr[] = { 0x0b, 0x34, 0x33, 0x32 };
    const int hexlen = 2; // outputting hex value with leading zero
    const int outstrlen = sizeof(bytearr) * sizeof(char) * sizeof(bytearr[0]) * hexlen;

    char *outstr;
    if ((outstr = malloc(outstrlen + 1)) == NULL) {
        printf("Failed to allocate memory");
        exit(1);
    }
    bzero(outstr, outstrlen + 1);

    int i;
    char tmp[hexlen + 1];
    for (i = 0; i &lt; (sizeof(bytearr) / sizeof(bytearr[0])); i++) {
        sprintf(tmp, "%.2x", bytearr[i]);
        strcat(outstr, tmp);
    }

    printf("Hexadecimal string:\n%s\n", outstr);

    free(outstr);

    return 0;
}


For what it's worth, after this review, my program ended up like this.
Well, aside from the fact that you could just reduce the program to outputting a single string-literal, let's look at it:


Excellent code-formatting. That's far too rare.
The calculation for outstrlen is all kinds of bent. Both middle factors don't make any sense.

sizeof(bytearr) * sizeof(char)   * sizeof(bytearr[0]) * hexlen
size_in_bytes   * bytes_per_byte * bytes_per_byte     * digits_per_byte

Just to be "safe", you zero outstr before overwriting it...
That isn't safe, that's redundant.
There's no good reason to use bzero() and make your program unportable. Just use memset() if you must.
Why do you print into a temporary buffer, only to append it to the output-string?


Print directly into the final destination. No need for an intermediate.
If you build a string bit by bit, don't be Shlemiel The Painter. No need to make a linear algorithm quadratic.

As you immediately exit the program, freeing memory is just busy-work. Still, as I'm not sure what you are trying to learn there, it might be excused.
As an aside, return 0; is implicit for main() in C99+ and C++. Not sure you that's really relevant, but here you go.


Equivalent program (C99+ or C++):

#include &lt;stdio.h&gt;

int main() {
    printf("Hexadecimal string:\n0b343332\n");
}