Simple random string generator in C It is just a simple piece of C code that generates random lenght random HEX srings. Any ideas how this code can be improved?

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

#define MAX_SIZE 256

int main() {
    time_t t;
    srand((unsigned) time(&amp;t));

    const char* digits = "0123456789ABCDEF";

    unsigned char str_len = rand() % MAX_SIZE;


    char* str = malloc((str_len + 1) * sizeof(char));
    if (str == NULL) {
        fprintf(stderr, "malloc failed\n");
        return -1;
    }

    char* init_ptr = str;
    char tmp_char;

    for (int i = 0; i &lt; str_len; i++) {
        if (i == 0) {
            do {
                tmp_char = *(digits + (rand() % 16));
            } while (tmp_char == '0');
        }
        *str = tmp_char;
        tmp_char = *(digits + (rand() % 16));
        str++;
    }

    *str = '\0';

    printf("%s", init_ptr);
    free(init_ptr);

    return 0;
}
You are effectively picking your first hex digit from "123456789ABCDEF" (no zero) and the subsequent digits from "0123456789ABCDEF".  Hence it might be better to adjust the first random pick:

// This assumes that str_len is at least 1.
*str = *(digits + (1 + rand() % 15));  // Pick first char in range 1..15
str++;

// For loop starts at 1 as str[0] already picked.
for (int i = 1; i &lt; str_len; i++) {
    *str = *(digits + (rand() % 16));  // Following chars in range 0..15
    str++;
}


That eliminates the tmp_char variable and the while loop, which makes the code a lot cleaner, to my eye anyway.