所以请对我温柔点。 我在当前的项目中遇到了一个小的内存泄漏,该项目是用C++开发一个小的dungeoncrawler的。 Valgrind显示我正在泄漏1块中的0字节在loss record1 of 38,Location level.cpp:6:0
中丢失。这行是我的构造函数定义。 我似乎找不到问题所在,因为在我读过关于Valgrind的文章之后,这个问题唯一可能的解释是,如果我创建了一个长度为0的数组,那么这个数组就会丢失,但在我的代码中并不是这样。
对于valgrind消息是如何发生的,还有其他的解释吗?
我宁愿不上传代码到这里,因为这个项目是相当大的,我不确定如果代码会有帮助。
Level::Level(const std::string& levelFileName)
{
auto nodes = loadNodesFromLevelFile(levelFileName);
std::vector<Node> switches;
std::vector<Node> portals;
for(const auto& node : nodes)
{
const auto nodeName = node.name;
if(nodeName == "Map Information")
{
setHeight(node.get<int>("rows"));
setWidth(node.get<int>("cols"));
m_gameboard = new Tile**[m_height];
for(auto row = 0; row < m_height; ++row)
{
m_gameboard[row] = new Tile*[m_width];
}
}
if(nodeName == "Wall")
{
auto col = node.get<int>("col");
auto row = node.get<int>("row");
m_gameboard[row][col] = new Wall(row, col);
}
if(nodeName == "Floor")
{
auto col = node.get<int>("col");
auto row = node.get<int>("row");
m_gameboard[row][col] = new Floor(row, col);
}
if(nodeName == "Door")
{
auto col = node.get<int>("col");
auto row = node.get<int>("row");
m_gameboard[row][col] = new Door(row, col);
}
if(nodeName == "Portal")
{
auto col = node.get<int>("col");
auto row = node.get<int>("row");
m_gameboard[row][col] = new Portal(row, col, nullptr);
portals.push_back(node);
}
if(nodeName == "Switch")
{
switches.push_back(node);
}
if(nodeName == "Character")
{
auto col = node.get<int>("col");
auto row = node.get<int>("row");
auto icon = node.get<char>("icon");
placeCharacter(new Character(icon), row, col);
}
}
for(const auto& portalNode : portals)
{
const auto row = portalNode.get<int>("row");
const auto col = portalNode.get<int>("col");
const auto destRow = portalNode.get<int>("destrow");
const auto destCol = portalNode.get<int>("destcol");
auto* portal = static_cast<Portal*>(m_gameboard[row][col]);
auto* destination = static_cast<Portal*>(m_gameboard[destRow][destCol]);
portal->setDestination(destination);
}
for(const auto& s : switches)
{
const auto row = s.get<int>("row");
const auto col = s.get<int>("col");
const auto destRows = s.get<std::vector<int>>("destrows");
const auto destCols = s.get<std::vector<int>>("destcols");
auto* sw = new Switch(row, col);
m_gameboard[row][col] = sw;
for(ulong i = 0; i < destRows.size(); ++i)
{
auto* target = m_gameboard[destRows[i]][destCols[i]];
sw->attach(dynamic_cast<Door*>(target));
}
}
}
这是我的级别(从第6行开始)的构造函数。