added safety checks for stack bounds