简体   繁体   中英

C code goes to infinite loop

Code goes to infinite loop. If I remove all lines inside inner for loop and replace with printf() it works properly. But keeping these lines, it goes to infinite loop.

How to resolve this issue? #include

#include <string.h>

void itoa(int, char[]);
void reverse(char[]);

int main()
{

    int i,j;
    for(i = 0;i<= 4; i++)
    {
        for (j = 0; j <= 9; j++)
        {
            char fileName[10]="A";
            char append[1];

                itoa(i,append);
            strcat(fileName,append);

            itoa(j,append);
            strcat(fileName,append);

            printf("i=%d j=%d\n", i,j);
            printf("%s\n", fileName);

        }
    }
}

void itoa(int n, char s[])
{
    int i, sign;

    if ((sign = n) < 0)  /* record sign */
        n = -n;          /* make n positive */
    i = 0;
    do {       /* generate digits in reverse order */
        s[i++] = n % 10 + '0';   /* get next digit */
    }
    while ((n /= 10) > 0);     /* delete it */
    if (sign < 0)
    s[i++] = '-';
    s[i] = '\0';
    reverse(s);
}
void reverse(char s[])
{
    int i, j;
    char c;

    for (i = 0, j = strlen(s)-1; i<j; i++, j--) {
        c = s[i];
        s[i] = s[j];
        s[j] = c;
    }
}

The program is invoking what is officially known as undefined behavior with this bit of code:

    char append[1];
    itoa(i,append);

itoa() is writing more than one element in append. Probably, a byte past append[] (namely append[1] ) is part of one of the loop variables ( main::i or main::j ) which leads to the infinite loop.

It's a whole lot simpler and cleaner to use sprintf for this kind of thing, eg

char fileName[32];
sprintf( filename, "A%d%d", i, j );
printf("%s\n", fileName);

Note, always make string buffers much bigger than they need to be.

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