vendredi 8 mai 2015

C wrong variable decrementing

So I am extremely confused right now. In the following code I initialize a for loop and attempt to decrement a size_t variable. However when doing this it appears that another size_t variable begins to decrement instead.

The code is as follows:

/**
 * sanitize_octet - Sanitizes a given octet for ipv4 calculation
 * requirements.
 *
 * @octet - Octet to be sanitized.
 *
 * returns:
 * NULL pointer - failure
 * Pointer to ret - success
 */
const char *sanitize_octet(const void *octet)
{
        char ret[4];
        size_t i = strlen(octet), j = i;

        if(i > 3) {
                printf("error: '%s' is not a valid octet.", (char *) octet);
                return NULL;
        }
        strcpy(ret, (char *) octet);
        while(i--) {
                if(!isdigit(ret[i])) {
                        printf("error: '%s' is not a valid octet.", ret);
                        return NULL;
                }
                if((int) ret[i] > 255) {
                        printf("error: '%s' is not a valid octet.", ret);
                        return NULL;
                }
        }
        if(j != 3) {
                i = 3 - j;
                for(j = 2; j > 1; j--) {
                        printf("j: %d, i: %d\n", j, i);
                        system("pause");
                }
        }
        puts(ret);
}

The function is still a work in process. What is really confusing me is this the for loop at the bottom. When initialized as for(j = 2; j > 1; j-- it actually decrements i instead of j and will simply execute until it crashes. However if I initialize the loop with j having a different value (e.g. 3) it executes as expected. I've never seen anything like this before and am extremely confused.

Here is a sample console output with j initialized to 2:

j: 2, i: 2
Press any key to continue . . .
1




j: 2, i: 1
Press any key to continue . . .
19

You can clearly see that i is being decremented and not j.

What could possibly be causing this?

Aucun commentaire:

Enregistrer un commentaire