
< 	while (i < sizeof(buf) && (pg - page < len) &&
---
> 	unsigned int buf_size = bufsize; // store the actual size of the allocated memory
> 	while (i < buf_size && (pg - page < len) &&
