繁体   English   中英

如何解决 C6386 警告?

[英]How to solve C6386 warning?

我正在编写一个简单的代码来从 .txt 文件中读取系统化数据,并收到警告“C6386:写入‘points’时缓冲区溢出:可写大小为‘num*8’字节,但可能写入‘16’字节”。 在我的情况下如何解决? 附上代码。

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

这只是一个警告,但它提供了很好的建议。 该文件包含的内容超过了num个项目? 警告告诉你,应该确保你写的内容不会超过数组的末尾。 具体来说:

此警告表明指定缓冲区的可写范围可能小于用于写入它的索引。 这可能会导致缓冲区溢出。 [msdn]

此代码不会产生警告(VS2019):

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

还有更多错误检查要添加。 如果file >> num; 失败? 如果num为负数怎么办? 如果points = new point[num]; 失败(返回nullptr )?

暂无
暂无

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

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