I know this is a common error so I tried to create a minimal example. I think this is because I try to free stack memory but I don't quite understand how I could do differently.
Maze.h
#pragma once
class Maze
{
public:
Maze();
Maze(unsigned int height, unsigned int width);
~Maze();
private:
unsigned int m_height;
unsigned int m_width;
char *entrance;
char *exit;
char *m_cells;
};
Maze.cpp
#include "Maze.h"
using namespace std;
Maze::Maze()
{
}
Maze::Maze(unsigned int height, unsigned int width) :
m_height(height),
m_width(width)
{
m_cells = new char[m_height * m_width];
entrance = nullptr;
exit = nullptr;
}
Maze::~Maze()
{
delete entrance;
delete exit;
delete[] m_cells; //this line causes the error
}
main.cpp that causes an error
#include <iostream>
#include <string>
#include "Maze.h"
using namespace std;
int __cdecl main(int argc, char **argv)
{
Maze maze;
maze = Maze(10, 10);
}
main.cpp without error
#include <iostream>
#include <string>
#include "Maze.h"
using namespace std;
int __cdecl main(int argc, char **argv)
{
Maze maze(10, 10);
}
What are the differences between the 2 mains ? why does the first one cause an error ? This is a problem because I want to declare maze but to initialize it later in my program. Here I only do it in two lines to create a minimal example.
The error occurs when the program closes so I think it's a memory deallocation problem. Indeed, when I remove delete[] m_cells; from the destructor, no error anymore.
What's happening exactly here ?