-2

im taking an oop course in c++ and was working on this assignment.

Class of a number represented as an array of integers,boolean expression as a sign of the number(true is +,false -). The program runs ok and does all what it needs,my problem is it is crashing on the end of the main when it gets to the return line.i found that by removing the destructor thst i have build the program runs ok,i tried to see where i am accessing memory that isnt allocated and couldnt find a problem with my code. The error that pops is heap error when i get to the last line in the Driver.cpp(main func)

thank you in ad

https://gist.github.com/michaelkosoy/630ff729aaa0a00a56786f3d8b84158f

  • Start commenting out code to make it the smallest example possible that exhibits the behaviour, then use a debugger or print statements to see where it is failing. – Romain Hippeau Apr 12 '20 at 13:47

1 Answers1

1

So you have an error in your copy constructor. After executing the copy constructor two numbers will share the same digits array. This means when the destructors are called the same memory will get deleted twice, resulting in a heap error.

You should write your code to ensure that every Number get it's own digit array in all circumstances.

You are also lacking an assignment operator, which means the same issue is going to happen if you assign one number to another.

Some further reading on this very important topic.

Note that the public function setArr that allows anyone to set the digit array of a Number is fundamentally wrong, because it means you cannot know where the array of a particular number has come from, and therefore you cannot safely delete that array. Same goes for the constructor that takes a digit array as a parameter.

john
  • 85,011
  • 4
  • 57
  • 81