Estimate buffer size

This change estimates the messages size before allocating a buffer. May solve issues like #1.