I have a problem which appear while processing with dynamically allocated memory. I was looking for similar problems but unfortunately none of solution helped me. Code of my class looks like below:
Declaration of my class:
class StructuralElement
{
private:
short rows;
short columns;
short *se;
friend class Morph;
public:
StructuralElement(char *path);
~StructuralElement();
short getAt(short row, short column);
int getSize();
};
Definition of my class:
StructuralElement::StructuralElement(char *path)
{
std::string line;
short rows=0, elements=0;
short it = 0;
std::string token;
try
{
std::ifstream file(path); //counting rows and columns in a file!
if (file.is_open() == NULL){ CannotOpenException ex; throw ex; }
if (file.fail()) { CannotOpenException ex; throw ex; }
while (getline(file,line))
{
rows++;
std::stringstream ss(line);
while (getline(ss, token, ' '))
{
elements++;
}
}
file.close();
this->rows = rows;
if (rows!=0)
this->columns = (elements/rows);
se = new short[elements];
std::ifstream file2(path);
if (!file2.is_open()) throw;
while (getline(file2, line))
{
std::stringstream ss(line);
while (getline(ss, token, ' '))
{
this->se[it++] = (static_cast<int>(token.at(0))-48);
}
}
file2.close();
}
catch (CannotOpenException &ex)
{
std::cerr << "Error occured! Unable to load structural element!";
}
}
StructuralElement::~StructuralElement()
{
if (se != NULL) delete[] se;
}
When program will have already finish working and there appear text :" Cick any key...." in a console, then I receive error:
Debug Assertion Failed
.......
Expression: _BLOCK_TYPR_IS_VALID(pHeap->nBlockUse)
When I change line
se = new short[elements];
to this one:
se = new short[];
Then I get message: Program has triggered in a breakpoint.
What I made wrong? Thank You in advance for any tips.
There's a very good chance you're doing a double delete.
Your class doesn't have a copy constructor or assignment operator, yet you're managing resources in a non-RAII fashion. That's most likely the cause of the problem. Implement a proper copy constructor and assignment operator that actually makes deep copies of your data members.