在 C++ 的复制构造函数中将内存分配给 2d 数组时收到“缓冲区溢出”警告

Getting "Buffer overrun" warnings while allocating memory to a 2d array in a copy constructor in C++

提问人:Joel 提问时间:12/16/2022 最后编辑:Stephen NewellJoel 更新时间:12/16/2022 访问量:120

问:

我正在使用 C++ 在 Visual Studio 2022 中创建一个吃豆子游戏。对于这个游戏,我有一个类“Map”来从文本文件加载地图并渲染它。我将文本文件中的数据保存在我的 Map 类中。我现在需要将此数据用于游戏中的其他对象。所以我试图为它制作一个复制构造函数。int** map

我猜我的复制构造函数工作正常。它将数据复制到新对象,并将内存分配给新指针,然后复制其中的值,而不会崩溃或导致错误。但我仍然收到这些警告:Map(const Map& original)

  • 警告 C6386:写入“map”时缓冲区溢出。
  • 警告 C6385:从“map”读取无效数据。
  • 警告 C6386:写入“map[y]”时缓冲区溢出。

这里有一个简化版本:

地图.h:

#pragma once
#include <stdlib.h>

class Map
{
public:
    // members would be private, only public for easier testing
    int height = 0, width = 0;
    int** map = nullptr;

    Map();
    Map(const Map& original);
    ~Map();
};

Map.cpp:

#include "Map.h"

Map::Map()
{
    // set map size
    height = 3;
    width = 2;

    // dynamically allocating memory for int** map
    map = (int**)malloc(height * sizeof(int*));
    if (!map)
        exit(1);
    for (int i = 0; i < height; i++)
        map[i] = (int*)malloc(width * sizeof(int));

    // giving map some values
    for (int y = 0; y < height; y++)
    {
        if (!map[y])
            exit(1);
        for (int x = 0; x < width; x++)
            map[y][x] = x + y;
    }
}

Map::Map(const Map& original)
{
    // copy map size
    height = original.height;
    width = original.width;

    // allocate new memory for the new map
    map = (int**)malloc(height * sizeof(int*));
    if (!map)
        exit(2);
    for (int i = 0; i < height; i++)
        map[i] = (int*)malloc(width * sizeof(int));     // Warning C6386: Buffer overrun while writing to 'map'.

    // copy the values from original.map to this->map
    for (int y = 0; y < height; y++)
    {
        if (!map[y])        // Warning C6385: Reading invalid data from 'map'.
            exit(2);
        for (int x = 0; x < width; x++)
            map[y][x] = original.map[y][x];     // Warning C6386: Buffer overrun while writing to 'map[y]'.
    }
}

Map::~Map()
{
    // freeing allocated memory
    for (int i = 0; i < height; i++)
        free(map[i]);
    free(map);
}

我只在复制构造函数中收到这些警告,但在构造函数中没有收到这些警告,但我基本上在它们中都写了相同的东西。 我现在想知道我是否应该忽略这些警告,或者我是否做错了什么。

我也尝试用 / 而不是 / 做同样的事情,它也有效,但我在那里没有收到任何警告。newdeletemalloc()free()

C++ dynamic-memory-allocation compiler-warnings 复制构造函数

评论

2赞 Hans Passant 12/16/2022
众所周知,代码分析警告是不可靠的。项目>属性 >代码分析 >常规>“启用Microsoft代码分析”= 否,它将停止抱怨。在 C++ 代码中支持 new[]。
4赞 MatG 12/16/2022
我宁愿使用零法则和std::vector
1赞 463035818_is_not_an_ai 12/16/2022
文档表明,完整的消息包含更多信息,并且是类似于“缓冲区溢出:访问'缓冲区名称',可写大小为'size1'字节,但可以写入'size2'字节:行:x,y”。您是否包含了完整的消息?
0赞 user4581301 12/16/2022
良好、安全、自我管理且简单的矩形阵列

答: 暂无答案