The proper way to do it is to factor out the length calc into a utility function that the API provides. Also the calculated buffer length is passed in to the function, and an error is returned if it's too small.