You need to use output.size() here, as the length is the entire buffer length which may be bigger (if it was allocated to be too big to begin with).