8

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.

The code is as follows:

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

}

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

"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.

adsisco
  • 287
  • 1
  • 2
  • 10

2 Answers2

9

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:

  • 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.

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
Ajay
  • 18,086
  • 12
  • 59
  • 105
  • Maybe you could explicitly state, that smart pointers should be used for owning pointers. There is nothing wrong with non-owning raw pointers. – MikeMB May 15 '16 at 20:30
3

Your code is fine and tools(especially analyzers) have their drawbacks — sometimes they generate false-positives. That's one of it. BTW, I checked your code on MSVS2015 and it gives me no warnings.

ixSci
  • 13,100
  • 5
  • 45
  • 79
  • you need to enable Code-Analysis – Ajay May 13 '16 at 08:59
  • @Ajay, I ran the code analysis tool against this code: *Running Code Analysis for C/C++...* – ixSci May 13 '16 at 09:01
  • You are right. Even I didn't get it (both 32-bit, 64-bit compilation). May be OP can shed more light on it. Is this exact code? Which VS version? (I have VS2015 U2) – Ajay May 13 '16 at 09:07