简体   繁体   English

C代码进入无限循环

[英]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. 如果我删除for循环内部的所有行并替换为printf()它将正常工作。 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. itoa()在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. 可能是append[] (即append[1] )后面的一个字节是导致无限循环的循环变量之一( main::imain::j )的一部分。

It's a whole lot simpler and cleaner to use sprintf for this kind of thing, eg 使用sprintf进行这种事情要简单很多,例如

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. 注意,始终使字符串缓冲区大于所需的大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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