简体   繁体   English

如何解决 C6386 警告?

[英]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".我正在编写一个简单的代码来从 .txt 文件中读取系统化数据,并收到警告“C6386:写入‘points’时缓冲区溢出:可写大小为‘num*8’字节,但可能写入‘16’字节”。 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?该文件包含的内容超过了num个项目? 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] [msdn]

This code does not produce the warning (VS2019):此代码不会产生警告(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;如果file >> num; fails?失败? What if num is negative?如果num为负数怎么办? What if points = new point[num];如果points = new point[num]; fails (returns nullptr )?失败(返回nullptr )?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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