简体   繁体   中英

How to solve C6386 warning?

I'm writing a simple code to read systemized data from.txt file, and got warning "C6386: Buffer overrun while writing to 'points': the writable size is 'num*8' bytes, but '16' bytes might be written". How to solve it in my case? Code attached.

struct point {
    int x, y;
};

void main()
{
    fstream file;
    point* points;
    int num, 
        i = 0;

    file.open("C:\\Users\\Den\\Desktop\\file.txt", fstream::in);
    if (!file.is_open()) {
        cout << "No file found\n";
        exit(1);
    }
    else {
        file >> num;
        points = new point[num];
    }

    while (file >> num) {
        points[i].x = num;   // <- here
        file >> num;
        points[i].y = num;
        i++;
    }

    file.close();
}

It is just a warning but it is giving good advice. What it the file contains more than num items? The warning is telling you that should make sure you don't write past the end of the array. Specifically:

This warning indicates that the writable extent of the specified buffer might be smaller than the index used to write to it. This can cause buffer overrun. [msdn]

This code does not produce the warning (VS2019):

int x, y;
while (i < num && (file >> x >> y)) {
    points[i].x = x;
    points[i].y = y;
    i++;
}

There is still more error checking to add. What if file >> num; fails? What if num is negative? What if points = new point[num]; fails (returns nullptr )?

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