1

我是一个 C 初学者,今天我遇到了一个困扰了我几个小时的问题,我减去了出现问题的子句。

我用Archlinux(gcc).

#include <stdio.h>

#define SIZE 10

int main()
{
    char s[SIZE]; 
    int i;
    for (i = 0; i < SIZE; )
        s[i++] = 'm';
    s[i++] = '\n';
    s[i] = '\0';
    printf("%s/D\n", s, i);

    return 0;
}

它工作没有错误。

输出为mmmmmmmmmm 11

删除了一条线。s[i++] = '\n';

#include <stdio.h>

#define SIZE 10

int main()
{
    char s[SIZE]; 
    int i;
    for (i = 0; i < SIZE; )
        s[i++] = 'm';
    s[i] = '\0';
    printf("%s %d\n", s, i);

    return 0;
}

“i”变成了0。输出:mmmmmmmmmm 0

但是一旦用 Cent OS(gcc) 编译。

“i”没有变成0。

回到Archlinux. 我进入了另一行。int a = i", to reference i;

#include <stdio.h>

#define SIZE 10

int main()
{
    char s[SIZE]; 
    int i;
    for (i = 0; i < SIZE; )
        s[i++] = 'm';
    s[i] = '\0';
    int a = i;
    printf("%s/D\n", s, i);

    return 0;
}

而这一次“i”没有变成0。

我是新手,有大神告诉我这是怎么回事?

如果这只是我犯的一些愚蠢的错误,请告诉我,我将删除该帖子。

谢谢!

4

2 回答 2

2

C arrays are zero-based so valid indices in your example are [0..SIZE-1]. At the end of your loop, i==SIZE. You then write to s[SIZE] which is one element beyond the end of your array. This has undefined consequences.

In your test, &s[SIZE] == &i so you write to i in both cases. In the first case, the ascii value of '\n' happens to be what you expected for i so you don't notice the bug. In the second case you get luckier, reset i to 0 and spot the array overflow.

The fix is to exit your loop one iteration sooner, leaving space for the null terminator in your char array

for (i = 0; i < SIZE-1; )
//                  ^^
于 2013-01-09T09:47:40.400 回答
0

此处数组的 theSize 定义为 10,但在 for 循环结束时,您尝试将其分配在第 11 位,这就是出现这种未定义行为的原因。

#include <stdio.h>

#define SIZE 10

int main()
{
    char s[SIZE]; 
    int i;
    for (i = 0; i < SIZE; )
        s[i++] = 'm';
    s[i] = '\0'; // here after end of your loop you are assigning a[10]='\0' that is makin it as undefined behaviour.
    int a = i;
    printf("%s/D\n", s, i);

    return 0;
}
于 2013-01-09T09:54:05.050 回答