I am creating a pacman game in Visual Studio 2022 with C++. For this game I have a Class "Map" to load the map from a text file and render it. I save the data from the textfile in int** map in my Map class. I now need this data for other objects in my game. So I was trying to make a copy constructor for it.
My copy constructor Map(const Map& original) works fine I guess. It copies the data to the new object and allocates memory to a new pointer and then copies the values in it without crashing or causing an error. But I still get these warnings:
- Warning C6386: Buffer overrun while writing to 'map'.
- Warning C6385: Reading invalid data from 'map'.
- Warning C6386: Buffer overrun while writing to 'map[y]'.
Here a simplified version:
Map.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);
}
I only get these warnings in the copy construcor but not in the constructor, but I have basically written the same stuff in both of them. I am now wondering if I should just ignore these warnings or if I have done something wrong.
I also tried doing the same thing with new / delete instead of malloc() / free() and it worked aswell but I did not get any warnings there.
 
    