Visual Studio的运行时检查失败#2 - 围绕堆栈变量“临时”被损坏

Visual Studio的运行时检查失败#2 - 围绕堆栈变量“临时”被损坏

问题描述:

我写了一个功能分区进行快速排序算法的元素进行排序cstrings数组Visual Studio的运行时检查失败#2 - 围绕堆栈变量“临时”被损坏

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复制到话

+0

'temp [MAXWORDLEN + 1]'为'\ 0'? – coderredoc

+0

@coderredoc是的,所以我可以使用c函数 –

+0

在'if'语句内部也使它相同...这就是我的意思。 '临时[MAXWORDLEN + 1]' – coderredoc

改变这样的:因为枢轴阵列具有

char temp[MAXWORDLEN + 1]; 

char temp[MAXWORDLEN]; 

本这个大小也是。


所以当temp是大小为6,它包含有6个字符单词,空终止将被重写,这意味着复制会失败,并调用未定义的行为。我们真的不知道要通过复制将什么垃圾值写入目标数组,如果有的话。

+0

不错@coderredoc ,,但我认为这是问题的答案。 – gsamaras