Isn't that because you don't clean the last connection ? you start your while with a i = length -1 right?