As mentioned earlier, pv have been around for ages and does this "the right way" (tm). Also, as an exercise, spot the potential buffer overflow in this source in less than 10 seconds for extra credits!
The correct solution would be a) check the length of format, and if it less than or equal to 4 but greater than 0, then copy the bytes, else, don't... I guess? Why is 4 such an arbitrary chosen number?
// new->format is allocated to 4 bytes
size_t len = strlen(format);
if(len > 0 && len <= 4) {
memcpy(new->format, format, len); //i to < 4
new->format[3] = '\0';
}
Or it just be better to allocate the new->length to the return value of strlen(format) + 1. new->format[4] = '\0';
is out of bounds, no?It's common to allocate your size needed plus 1 for the NULL byte. But this programmer only allocates 4 bytes.. with no thought of the NULL byte at the end.
Dates back to 2002.