I am writing a program to read in 2 4-digit char patten from the user and then replicate each pattern to 32 digits. (let me call this stump_si) then i need to alternate the 2 32-digit patterns and write it into a file.
I am able to generate the patterns and when i give input pattern as 3 digits (instead of 4) i get the file written. But when i give 4 digits i get segmentation error (coredump)
My code:
[code]int main()
{
//clrscr();
char patt1[10];
char patt2[10];
int length;
char stump_si[32];
cout<<"Enter the 1st pattern (4 digits)";
cin>>patt1;
cout<<"Enter the 2nd pattern(4 digits)";
cin>>patt2;
cout<<"Enter the number of times the patterns should be inserted";
cin>>length;
ofstream fout;
fout.open("pattern");
//generating the pattern
for (int i=0;i<length;i++)
{
if(i%2==0)
{
strcpy(stump_si,patt1);
for (int j=0;j<7;j++) //generating 32 from the 4 bits
{
strcat(stump_si,patt1);
}
cout<<stump_si<<endl;
fout<<stump_si[3]<<endl;
}
else
{
strcpy(stump_si,patt2); //generating 32 bits from 4 bits
for (int j=0;j<7;j++)
{
strcat(stump_si,patt2);
}
cout<<stump_si<<endl;
fout<<stump_si[3]<<endl;
}
}
Accessing array elements out of bounds invokes undefined behavior. That means that anything is allowed to happen. You can't assume the program will crash. Sometimes it appears to "work" like nothing was wrong.