gpt4 book ai didi

c++ - 遇到 STATUS_STACK_BUFFER_OVERRUN

转载 作者:行者123 更新时间:2023-11-30 18:54:51 31 4
gpt4 key购买 nike

我已经搜索了这个特定的错误,发现根本问题涉及循环计数错误并导致程序超出数组的界限。

但是,当我将每个数组降低到数组开始丢失输出数据的程度后,它继续抛出相同的错误。我对 C/C++ 仍然是新手,但任何对此的深入了解将不胜感激。

程序似乎运行到了最后,甚至回到了main方法。

#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)

关于c++ - 遇到 STATUS_STACK_BUFFER_OVERRUN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29444364/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com