c++ - _Block_Type_Is_Valid (pHead->nBlockUse) Deleting stack memory? -
this question has answer here:
- what rule of three? 8 answers
i know common error tried create minimal example. think because try free stack memory don't quite understand how 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 error }
main.cpp causes 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 differences between 2 mains ? why first 1 cause error ? problem because want declare maze initialize later in program. here in 2 lines create minimal example.
the error occurs when program closes think it's memory deallocation problem. indeed, when remove delete[] m_cells; destructor, no error anymore.
what's happening here ?
the line:
maze = maze(10, 10);
is creating copy of object, happens is:
maze(10, 10)
- constructs new object, allocates memoryoperator new
,operator new[]
.- maze assigned copy of object made in 1. done assigning pointer values of first 2nd.
- then object 1 destructed, deletes pointers.
- maze goes out of scope, deletes pointers again, here crash.
to solve read rule of 3, need add copy constructor , assignment operator.
for example:
// copy constructor maze::maze(const maze& other) { // call assignment operator, saves duplicating assignment operator code in here. *this = other; } // assignment operator maze& maze::operator = ( const maze& other ) { if ( != &other ) { // todo: copy pointers, not assigning them, use operator new , copy data "other" destruct , delete pointers, hence problem } return *this; }
if using c++11 use move construction/assignment too, swap pointers, , set source objects pointers null/nullptr.
in c++11 can use default , delete keyword prevent use of constructors have no implemented shouldn't called, example:
class foo { public: foo() = default; // prevent copying foo(const foo&) = delete; foo& operator = ( const foo& ) = delete; int x = 0; };
this cause following fail @ compilation stage:
foo a; = foo();
Comments
Post a Comment