简体   繁体   中英

Reversing input every two characters

I've been trying to make a program that takes an address and reverses it for every two characters. An example input would be "0xefba5896" and ideally it's output would be "\\x96\\x58\\xba\\xef". The trouble I'm getting is that the first few bytes work, but the last one doesn't print. My code is below:

     int i;
     char *add =  argv[1];
     char rev[8];
     char xa[2];
     strncpy(rev, &add[2], strlen(add));   
     for (i = strlen(rev) - 2; i > -2; i-=2) {
                if (i == 0) {
                    strncpy(xa, &rev[0], 2);
                 } else {
                    strncpy(xa, &rev[i], 2);
                    xa[2] = '\0';
            }
                printf("\\x%s", xa);
     }

If I input "0xefba5896" my output is:

\x96\x58\xba\x

If the answer is obvious to someone, please forgive me. I've been learning C for only about a week. Any help would be immensely appreciated!

It makes no sense to pass strlen(add) as the limiting factor to strncpy , if add is longer than 10, you will still overflow rev !

You have to pass the size of the destination , not the size of the source. So the correct call is

strncpy(rev, add+2, sizeof rev);
rev[sizeof(rev) - 1] = 0;

Also note that strncpy does not necessarily write the '\\0' -terminating byte if the destination is not long enough, so you should always set the '\\0' -terminating byte yourself.

Also note that xa[2] = '\\0'; overflows xa , because the size of xa is 2, so the maximal index is 1 . If you want to store 2 characters in xa , then xa needs to be of at least dimension 3. Same goes for rev . So You have to declare xa as this:

char rev[9];
char xa[3];

So when you use strncpy , you should use it like this:

char dest[8];
strncpy(dest, src, sizeof dest);
dest[sizeof(dest) - 1] = 0;

So you can rewrite your program like this:

int main(int argc, char **argv)
{
    if(argc != 2)
    {
        fprintf(stderr, "usage: %s address\n", argv[0]);
        return 1;
    }

    size_t len;
    char *add =  argv[1];
    char rev[9];
    char xa[3];  

    strncpy(rev, add + 2, sizeof rev);
    rev[sizeof(rev) - 1] = 0;

    len = strlen(rev);

    if(len & 1)
    {
        fprintf(stderr, "Invalid length of address, needs an even number of characters\n");
        return 1;
    }

    for(size_t i = len - 2; i >= 0; i -= 2)
    {
        strncpy(xa, rev + i, sizeof xa);
        xa[sizeof(xa) - 1] = 0;

        printf("\\x%s", xa);
        fflush(stdout);
    }

    putchar('\n');

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM