c++ - Visual Studio 运行时检查失败 #2 - 变量 'temp' 周围的堆栈已损坏

标签 c++ arrays runtime-error c-strings strcpy

我已经编写了一个函数来对元素进行分区,以用于对 cstring 数组进行排序的快速排序算法

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

但是,当我运行该程序时,出现运行时检查失败。 MAXWORDLENGTH 为 6,数组中所有单词的长度都在 4-6 个字符之间。所以我很困惑为什么变量 temp 似乎无法复制到索引 partitionIndex 处的单词

最佳答案

改变这个:

char temp[MAXWORDLEN];

为此:

char temp[MAXWORDLEN + 1];

因为枢轴数组也有这个大小。


因此,当 temp 的大小为 6 并且它包含的单词有 6 个字符时,空终止符将被覆盖,这意味着复制将失败并调用未定义的行为。我们真的不知道通过复制将哪些垃圾值写入目标数组(如果有的话)。

关于c++ - Visual Studio 运行时检查失败 #2 - 变量 'temp' 周围的堆栈已损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47362574/

相关文章:

oracle11g - 代表 :50125:rwbuilder. conf :java. lang.NullPointerException

c++ - 在curl中请求期间是否有网络断开的回调

javascript - KnockoutJS - 无法从纯 JSON 数组映射模型

c++ - QFile读取超时

ios - 在 iPhone View 中转到数组中的下一张和上一张图片的好计数器吗?

javascript - 查找嵌套数组中的最高值,然后记录该对(数字和字符串)

excel - 运行时错误 6 : Overflow: Excel VBA

.net - 程序集加载问题

c++ - 如何在MFC中使用Document/View架构

c++ - 使用参数包将 lambda 转换为 std::function