VS2015:[C6386] 写入时缓冲区溢出(即使是相同的索引值) [英] VS2015: [C6386] Buffer Overrun while writing (even for same index value)

查看:114
本文介绍了VS2015:[C6386] 写入时缓冲区溢出(即使是相同的索引值)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在 Visual Studio 2015 中遇到 [Analyze -> Run Code Analysis] 提出的有趣问题时,我正尝试在 C 中实现合并排序.

I'm trying to implement merge sort in C when I came across something interesting raised by [Analyze -> Run Code Analysis] in Visual Studio 2015.

代码如下:

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,但在第一个版本中,我收到警告:

Even though both version of rightCount essentially evaluates to 2, in the first version, I get the warning:

写入 'R' 时缓冲区溢出:可写大小为 '(unsigned int)rightCount*sizeof(int)' 字节,但可能写入 '8' 字节."

"Buffer overrun while writing to 'R': the writable size is '(unsigned int)rightCount*sizeof(int)' bytes, but '8' bytes might be written."

知道为什么会这样吗?期待听到您的回答.

Any idea why this is the case? Looking forward to hear your answers.

推荐答案

Visual C++ 代码分析工具集可能并不总是提供最好的警告.它试图为您提供最好的警告集,以修复一些可能在运行时出现的潜在问题/错误.您有几个选择:

Visual C++ Code Analysis toolset may not always offer the best warnings. It tries to give you the best set of warnings to fix some potential issues/errors that may creep in at runtime. You have a few options:

  • 使用 #pragma 指令禁用代码周围的给定警告.
  • 使用 C++ 结构:newmake_unique
  • (不推荐)是完全忽略警告并继续前进.
  • Disable the given warning around the code using #pragma directive.
  • Use C++ constructs: new, make_unique etc.
  • (Not recommended) is to ignore the warning altogether and move on.

理想情况下,您应该始终使用较新的智能指针原语,例如 unique_ptrshared_ptr 等.它们不仅为您分配内存,而且会解除调用堆栈中抛出的任何异常.你根本不需要输入*

You should ideally always user newer smart pointers primitives like unique_ptr, shared_ptr etc. They not only allocate memory for you but deallocate on any exception thrown across the call stack. You don't need to type * at all!

auto buffer = make_unique<int[]>(10); // 10 integers

这篇关于VS2015:[C6386] 写入时缓冲区溢出(即使是相同的索引值)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆