2
votes

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
What is i? What is num (the first value)? I mean their values for your input file.txt ;) - gsamaras
How sure are you that there aren't more than the first read into num entries in the file? Be a good time to edit the question to add a small sample input that triggers the error so we can see what's up. - user4581301
i - just an iterator, num - integer - user9882409
user4581301, there is not an error, just warning message in visual studio. Program is working fine, as I want, but I just wonder why there is such an error. - user9882409

1 Answers

1
votes

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