STATUS_STACK_BUFFER_OVERRUN遇到了

STATUS_STACK_BUFFER_OVERRUN encountered

我搜索了这个特定的错误,发现潜在的问题涉及循环计数错误并导致程序超出数组的范围。

但是,在我将每个数组降低到数组开始丢失输出数据的点后,它继续抛出相同的错误。我对 C/C++ 还是个新手,但如果对此有任何见解,我将不胜感激。

程序似乎 运行 一直到最后,甚至 returns 到主要方法。

#include <stdio.h>



void sortAr(char[]);

    int main ()
{
    char a='y';
    char b,i;
    char c[20];
    int x=0,n=0,z=0;
    while (x<=19)
    {
        c[x]='@'; 
        x++;
    }

    printf("Enter 20 letters: \n"); 

    while (z<=20) //(The '=' caused my problem, removed and it runs fine.)
    {
        z++;
        x=0;
        b='y';
        scanf("%c",&i);
        while (x<=19)
        {
            if (c[x]==i)
                b='n';
            x++;
        }

        if (b=='y')
        {
            c[n]=i;
            n++;
        }
    }
    printf("\n");
    printf("The nonduplicate values are: \n");      

    sortAr(c);

}





    void sortAr(char ar[])
    {
        char z;
    for (int i = 0; i <= 19; i++) 
    {
        for (int j=i+1; j <= 19; ++j)
        {
            if (ar[i]>ar[j])
            {
                z =  ar[i];
                ar[i] = ar[j];
                ar[j] = z;
            }
        }
    }
    for (int i = 0; i < 20; i++) 
    {
        if(ar[i]=='@')
            continue;
        printf("%c ", ar[i]);
    }
    printf("\n");
    }

我在以下位置发现错误:

while (z<=20)

原因是数组执行的次数多于数组在内存中索引的次数,因此会覆盖比预期更多的字符。结果它写入了未分配给它的内存并导致 Stack_Buffer_Overrun.

Trace Z:

Z was initialized to 0.
Array was initialized to 20.

While loop starts with Z as the counter for read-ins.
z=0 array=1 1st run,
z=1 array=2 2nd run,
z=2 array=3 3rd run,
z=3 array=4 4th run,
...
z=20 array=21 21st run. (Array cannot hold 21st character and results in Stack_Buffer_Overrun.)

解决方案:

change while(z<=20) -> while(z<20)