Segmentation Fault

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;
}
}


fout.close();

return 0;
}[\code]

can someone help me solve this issue?
Last edited on
strcpy is used for null-terminated strings. You're not using null-terminated strings.

http://www.cplusplus.com/reference/clibrary/cstring/strcpy/
cin>> will null terminate the string so I don't think that is a problem here.

Strings are null terminated so stump_si has only room for 31 characters. If you make stump_si a bit larger it will probably work better.
thanks a lot
Increasing the size of stump_si solved the problem.

But i dont understand, when i was not using fout the program ran perfectly. Even with stump_si size being 32. Why was that?
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.
Thanks for your help
Topic archived. No new replies allowed.