I have been studying for my programming exam lately and I have encountered some problems that I hope you could explain to me. I have been doing exams from the last years to practise and here is the portion of the code that I would love some help with:
In the exam, they clearly state that there is an important problem with the Document(int max) constructor and to solve the problem by doing necessary changes to it. I have no idea what's wrong with it, in fact, I compiled the program and the output was this:
The Document class acts as if there exists an array of Sentence (with length max) assigned to the sentences variable. This array could be allocated in the constructor but isn't.
So the sentences variable holds garbage and when its used in NewSentence some arbitrary part of memory will be overwritten and the program may crash.
In addition to nuzzle's point about sentences being uninitialized, I'll point out that just having a Sentence pointer instead of a proper container class such as a list, and a constructor that arbitrarily constrains the number of sentences is a pretty goofy design.
In the exam, they clearly state that there is an important problem with the Document(int max) constructor and to solve the problem by doing necessary changes to it.
Your teacher taught you that main() returns void? Get another teacher. The main() function returns an int.
I can break your class easily with a two-line main() program.
Code:
int main()
{
Document doc(10);
Document doc2 = doc;
}
You note that at the end, you're deleting the same pointer value twice, once for doc and another for doc2. This leads to undefined behaviour, possibly a crash or some sort of diagnostic. How you fix the problem -- that is for later.
Bookmarks