Use strlen() inside the function instead of supplying input length as a parameter. Almost every occurrence of the call was preceded by strlen() call.