简体   繁体   中英

Buffer Overrun - Can't seem to locate the porblem

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.

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++)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM