fix fencepost problem which caused memory violation