c++ - 如何解决C6386警告?

标签 c++ visual-studio warnings

我正在编写一个简单的代码来从 .txt 文件读取系统化数据,并收到警告“C6386:写入“点”时缓冲区溢出:可写大小为“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)怎么办?


更新了完整的错误检查:

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

将来,请考虑在原始数组上使用 std::vector

关于c++ - 如何解决C6386警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58563272/

相关文章:

c++ - 为什么VC++/MFC没有main函数?

c# - Visual Studio 中的输出窗口没有调试选项

php - 我不知道的 SQL 错误消息 : "Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource"

javadoc -Xdoclint 一直标记我的(可选)匿名类,因为它显然没有评论

c++ - 分配 : error for object: pointer being freed was not allocated

c++ - 将字符串打印到屏幕上后更改 C++ 中的字符串

c++ - 需要有关宏定义的帮助

c# - 当前上下文中不存在名称 'nameof'

visual-studio - 保存解决方案构建顺序的位置

c - Rust 的 (void) 变量替代品