I have searched for this particular error and found the underlying issue involves loop counts being wrong and causing the program to exceed it's bounds for the array.
However, after I lowered each array to the point where the array began to lose data on output, it continued to throw the same error. I am still new to C/C++ but any insight into this would be greatly appreciated.
The program seems to run through to the very end and even returns to the main method.
#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");
}
I found the error at:
while (z<=20)
The reason is the array would overwrite more characters than intended by executing more times than the array had indexed in the memory. As a result it wrote into memory that was not allocated to it and caused the 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.)
Solution:
change while(z<=20) -> while(z<20)