diff --git a/lib/escape.c b/lib/escape.c
index 048fd0f997910883f4ac51bd02a59fdb42a61c65..74d8deea82d68c2c4f7807da71bb5f6c6cb36be6 100644
--- a/lib/escape.c
+++ b/lib/escape.c
@@ -100,7 +100,7 @@ char *curl_unescape(char *string, int length)
                             the "query part" where '+' should become ' '.
                             RFC 2316, section 3.10 */
   
-   while(--alloc) {
+   while(--alloc > 0) {
       in = *string;
       if(querypart && ('+' == in))
          in = ' ';
@@ -113,6 +113,7 @@ char *curl_unescape(char *string, int length)
         if(sscanf(string+1, "%02X", &hex)) {
           in = hex;
           string+=2;
+          alloc-=2;
         }
       }