You should be allocating a stack buffer here, not a heap buffer that you just throw away.  Same goes for all of these actually, better to allocate after you know the length.