memcpy(temp,buf2,sizeof(buf2));
This is wrong. sizeof(buf2) is sizeof(char *), size of a pointer, 4 with 32bit addressing systems, 8 with 64bit addressing ones.
It should be memcpy(temp,buf2,size-1);
Anyway, this code is pretty inefficient, it should use larger buffer size, and preferably linked list of chunks, rather than excessive copying which kills cache.