you should use buffer_addf(but, "%d:%s", len, str); This would dramatically simplify the function