It looks like you should check here if there is enough space available in p before copying buf.