Reputation:
I am attempting to create a permutation, and I receive this strange error when I finish my problem:
Stack around the variable "temp" was corrupted
the segment of the variable is within a nested for loop:
for(int i = 0 ; i < str_length ; i++)
{
for(int j = 0 ; j < str_length ; j++)
{
char temp[1];
temp[1] = text[i];
text[i] = text[j];
text[j] = temp[1];
cout << text << endl;
}
}
text is initialized outside of the for loop as a string, and I get the same error when i make temp[1] into a char or an int. The program works fine but I am concern why I am receive this error, does anyone know why?
Upvotes: 0
Views: 576
Reputation: 3574
temp[1] does not exist, you should be doing temp[0]. Or alternatively, like this:
char temp;
temp = text[i];
text[i] = text[j];
text[j] = temp;
or
char temp[1];
temp[0] = text[i];
text[i] = text[j];
text[j] = temp[0];
Upvotes: 10
Reputation: 564403
You just need to use char temp;
and acces it as temp = text[i];
, etc.
You're accessing a point on the stack one byte PAST temp, which is invalid. In this case, since you only want a single char, there's no need for an array at all.
Upvotes: 14