0

I am working on a sample test in the site: https://www.testdome.com/for-developers/solve-question/9808 I added two destructors for base class and derived class respectively to release the memory allocated by constructors. The first two requirements of this question are solve successfully, but the result give a fail as: Using timed multiple choice test as multiple choice test: Memory limit exceeded

My modified code as given below, I will appreciate if you can help to fix the fail...

#include <iostream>
#include <string>

class MultipleChoiceTest
{
public:
    MultipleChoiceTest(int questionsCount)
    {
        this->questionsCount = questionsCount;
        answers = new int[questionsCount];
        for (int i = 0; i < questionsCount; i++)
        {
            answers[i] = -1;
        }
    }

    void setAnswer(int questionIndex, int answer)
    {
        answers[questionIndex] = answer;
    }

    int getAnswer(int questionIndex) const
    {
        return answers[questionIndex];
    }
    ~MultipleChoiceTest()
    {
        delete answers; // release memory
    }
protected:
    int questionsCount;

private:
    int* answers;
};

class TimedMultipleChoiceTest : public MultipleChoiceTest
{
public:
    TimedMultipleChoiceTest(int questionsCount)
        : MultipleChoiceTest(questionsCount)
    {
        times = new int[questionsCount];
        for (int i = 0; i < questionsCount; i++)
        {
            times[i] = 0;
        }
    }

    void setTime(int questionIndex, int time)
    {
        times[questionIndex] = time;
    }

    int getTime(int questionIndex) const
    {
        return times[questionIndex];
    }
    ~TimedMultipleChoiceTest()
    {
        delete times; // release memory
    }
private:
    int* times;
};

#ifndef RunTests
void executeTest()
{
    MultipleChoiceTest test(5);
    for (int i = 0; i < 5; i++)
    {
        test.setAnswer(i, i);
    }

    for (int i = 0; i < 5; i++)
    {
        std::cout << "Question " << i + 1 << ", correct answer: " << test.getAnswer(i) << "\n";
    }
}

int main()
{
    for (int i = 0; i < 3; i++)
    {
        std::cout << "Test: " << i + 1 << "\n";
        executeTest();
    }
}
#endif  
Sunny Lei
  • 181
  • 1
  • 3
  • 15
  • 2
    Not sure if it solves the problem, but for one you should clean up answers by `delete[] answers` instead of `delete answers` (and same for `times`) – CompuChip Jul 24 '17 at 11:44
  • As a side note, you should do boundaries check in your code. calling `getAnswer(-1);` at the moment is undefined behaviour. – IlBeldus Jul 24 '17 at 11:50

1 Answers1

2

you should use delete [] instead of delete to deallocate dynamic arrays.

Also, you don't seem to use the derived class but, nevertheless, the destructor in MultipleChoiceTest should be virtual

IlBeldus
  • 1,040
  • 6
  • 14