我尝试在C中实现合并排序,当我遇到由Visual Studio 2015中的[分析 - >运行代码分析]引发的一些有趣问题时。VS2015:[C6386]写入时缓冲区溢出(即使对于相同的索引值)
的代码如下:
void MergeSort_r(int A[], int n)
{
// A = {1, 3, 2}
// n = 3
int rightCount;
int* R;
if (n < 2) return;
// version 1: rightCount = 2
rightCount = n - (n/2);
// version 2: rightCount = 2
rightCount = n - 1;
R = (int*) malloc(rightCount * sizeof(int));
if (R) {
for (int i = 0; i < rightCount; i++) {
R[i] = A[i];
}
free(R);
}
}
尽管两个版本rightCount基本上计算为2,在第一个版本,我得到警告:
"Buffer overrun while writing to 'R': the writable size is '(unsigned int)rightCount*sizeof(int)' bytes, but '8' bytes might be written."
任何想法,为什么日是这样吗?期待听到你的答案。
[请参阅此讨论,为什么不在'C'中投射'malloc()'和家族的返回值。](http://stackoverflow.com/q/605845/2173917)。 –
@Sourav:在c + +(这是在VS中的默认值),你必须。 – MikeMB
@MikeMB是不是像我们有C编译器来编译C代码?无论如何,我们应该使用它。顺便说一句,这只是一个内容丰富的评论。 –