Fix handling of snprintf return values and buffer size calculations

This makes the code more secure in the case the allocated string buffers aren't large enough.