Given that the maximum size of a UDP packet is 65507 , you can simply allocate one 64k buffer for all your recvfrom() - after you copy it, read the size, select a new buffer and make a copy of your packet exactly in the right size.
It is a little wasteful to copy batch data so much, but it will allow you to allocate buffers with the right size.
Or, if you know that your peer will never generate packets larger than 8 thousand in size due to the architecture of your application, you can simply allocate 8 thousand buffers and lose space. Awareness of memory usage is important, but sometimes just burning an extra page simplifies the code.
sarnold
source share