首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Visual studio运行时检查失败#2 -变量'temp‘周围的堆栈已损坏。

Visual studio运行时检查失败#2 -变量'temp‘周围的堆栈已损坏。
EN

Stack Overflow用户
提问于 2017-11-18 04:41:23
回答 1查看 2K关注 0票数 0

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

代码语言:javascript
复制
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的单词中

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-11-18 04:53:07

改变这一点:

代码语言:javascript
复制
char temp[MAXWORDLEN];

对此:

代码语言:javascript
复制
char temp[MAXWORDLEN + 1];

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

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47362574

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档