1
votes

I'm trying to locate the problem in this simple example code that produces the "Buffer Overrun Warning", and after looking at it for a while I decided to post this in hope of someone maybe seeing the error in my code?

Message: Warning C6386 Buffer overrun while writing to 'tmpArray': the writable size is 'line.public: unsigned int __thiscall std::basic_string,class std::allocator >::length(void) const ()*12*4' bytes, but '52' bytes might be written.

Example that produces the warning:

#define STEP 12

void main()
{
    std::string line("Hello!");

    float* tmpArray = new float[line.length() * STEP];

    unsigned int v = 0;

    for (unsigned int i = 0; i < line.length(); i++)
    {
        tmpArray[  v  ]  = 0.0f;
        tmpArray[v + 1]  = 0.0f;
        tmpArray[v + 2]  = 0.0f;
        tmpArray[v + 3]  = 0.0f;
        tmpArray[v + 4]  = 0.0f;
        tmpArray[v + 5]  = 0.0f;
        tmpArray[v + 6]  = 0.0f;
        tmpArray[v + 7]  = 0.0f;
        tmpArray[v + 8]  = 0.0f;
        tmpArray[v + 9]  = 0.0f;
        tmpArray[v + 10] = 0.0f;
        tmpArray[v + 11] = 0.0f;

        v += STEP;
    }

    delete[] tmpArray;
}

I don't see where I'm stepping into memory that doesn't belong to tmpArray, I mean the buffer is allocated precisely based on the same values as the string's length and the step-size.

1
Looks like a correct program and bogus warning to me. I don't know why the compiler would give this warning, since it's unlikely it can actually predict at compile time either the value of line.length() or even whether values of line.length() will always be the same on each call. (And if 52 bytes is too many, apparently the compiler suspects the first line.length() could be 1, but the next could be greater?) Maybe someone figured the words "might be" mean they can give the warning any time the compiler has no clue if it's safe? - aschepler
Hey, thank you for the response! That's what I was suspecting as well, because no matter how long and hard I look at it I can't see the problem... I've tried copying the line.length() into an unsigned int and use that in both places, and now the warning is gone... weird... - GDN9
If this is the exact code, it could be a compiler bug - M.M
What is your compiler (which version)? - Steve
It's odd that the array size is actually 12 * 5 * 4 = 240 bytes (bytes is mentioned in the error). The array is 12 * 5 = 60 floats, which is still over the number 52 in the error message. Why "52"? - Steve

1 Answers

0
votes

Thanks to aschepler who commented above, the solution to this turned out to be to copy the value returned by .length() into a const unsigned int, and then use that in both places, like so:

const unsigned int lineLength = line.length();

Allocation:

float* tmpArray = new float[lineLength * STEP];

For loop:

for (unsigned int i = 0; i < lineLength; i++)