Fixes incorrect out of memory error and overflow of allocated buffer