Note that there are some explanatory texts on larger screens.

plurals
  1. POIdentify the memory leaks
    primarykey
    data
    text
    <p>I'm trying to answer some past paper questions that I've been given for exam practice but not really sure on these two, any help be greatly appreciated. (Typed code up from image, think it's all right).</p> <p>Q1: Identify the memory leaks in the C++ code below and explain how to fix them. [9 marks]</p> <pre><code>#include &lt;string&gt; class Logger { public: static Logger &amp;get_instance () { static Logger *instance = NULL; if (!instance){ instance = new Logger(); } return *instance; } void log (std::string const &amp;str){ // ..log string } private: Logger(){ } Logger(Logger const&amp;) { } Logger&amp; operator= (Logger const &amp;) { } ~Logger() { } }; int main(int argcv, char *argv[]){ int *v1 = new int[10]; int *v2 = new int[20]; Logger::get_instance() . log ("Program Started"); // .. do something delete v1; delete v2; return 0; } </code></pre> <p>My answer is that if main never finishes executing due to an early return or an exception being thrown that the deletes will never run causing the memory to never be freed. I've been doing some reading and I believe an auto_ptr would solve the problems? Would this be as simple as changing lines to?? :</p> <pre><code>auto_ptr&lt;int&gt; v1 = new int[10]; auto_ptr&lt;int&gt; v2 = new int[20]; v1.release(); delete v1; </code></pre> <p>Q2: Why do virtual members require more memory than objects of a class without virtual members?</p> <p>A: Because each virtual member requires a pointer to be stored also in a vtable requiring more space. Although this equates to very little increase in space.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload