[英]Visual studio Run-Time Check Failure #2 - Stack around the variable 'temp' was corrupted
I've written a function to partition elements for a quick sort algorithm for sorting an array of cstrings 我已经编写了一个函数来对元素进行分区,以实现对cstrings数组进行排序的快速排序算法
void partition(char words[][MAXWORDLEN + 1], int start, int end, int& partitionIndex) {
char pivot[MAXWORDLEN + 1]; //choose last element to be the pivot
strcpy(pivot, words[end]);
partitionIndex = start; //partition index is initalized to the first index
for (int i = start; i < end; ++i) { //iterate through the array
if (strcmp(words[i], words[end]) < 0) {
char temp[MAXWORDLEN];
strcpy(temp, words[i]); //swap the element with the element corresponding to the partition index
strcpy(words[i], words[partitionIndex]);
strcpy(words[partitionIndex], temp);
partitionIndex++;
}
}
cout << end << endl;
char temp[MAXWORDLEN + 1];
strcpy(temp, words[end]);
strcpy(words[end], words[partitionIndex]);
strcpy(words[partitionIndex], temp);
} }
However, when I run the program, I get a run time check failure. 但是,当我运行程序时,出现运行时检查失败。 MAXWORDLENGTH is 6 and all words in the array are between 4-6 characters long.
MAXWORDLENGTH为6,数组中所有单词的长度在4-6个字符之间。 So I'm confused why the variable temp can't seemed to be copied to words at index partitionIndex
所以我很困惑为什么变量temp似乎无法复制到索引partitionIndex的单词上
Change this: 更改此:
char temp[MAXWORDLEN];
to this: 对此:
char temp[MAXWORDLEN + 1];
since the pivot array has this size too. 因为数据透视表数组也具有此大小。
So when temp
was of size 6 and the word it contains had 6 characters, the null terminator would be overwritten, meaning that the copy would fail and invoke Undefined Behavior. 因此,当
temp
的大小为6且包含的单词有6个字符时,空终止符将被覆盖,这意味着该副本将失败并调用未定义行为。 We don't really know what garbage values are going to be written into the target array via copying, if any. 我们真的不知道将通过复制将哪些垃圾值写入目标数组(如果有)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.