Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

1 Answers

It is just a warning but it is giving good advice. What if 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)?


Updated with full error checking:

struct point {
    int x, y;
};

void main()
{
    ifstream file("C:\\Users\\Den\\Desktop\\file.txt");
    if (!file) {
        cerr << "No file found\n";
        exit(-1);
    }

    int num;
    if (!(file >> num) || num <= 0) {
        cerr << "invalid num\n";
        exit(-1);
    }
    point *points = new point[num];
    if (!points) {
        cerr << "new failed\n";
        exit(-1);
    }
    int num_items = 0;
    while (num_items < num && file >> points[num_items].x >> points[num_items].y) {
        num_items++;
    }
    // Do some work here
    delete [] points;
}

In the future, consider using std::vector over raw array.

like image 189
Johnny Mopp Avatar answered Nov 19 '25 17:11

Johnny Mopp