Note that there are some explanatory texts on larger screens.

plurals
  1. POc++ how to solve my memory leak?
    primarykey
    data
    text
    <p>Consider the following implemntation of a Binary class representation of an integer:</p> <pre><code>class Binary { private: int *digits; int first1; public: Binary() { digits = new int[128]; digits[0]=0; first1=0; } ~Binary() { cout&lt;&lt;"deleting"&lt;&lt;endl; delete [] digits; } Binary(const Binary&amp; b){ digits = new int[128]; memcpy(digits,b.digits,128*sizeof(int)); first1=b.first1; } explicit Binary(double x){ int n=(int)x,i; digits = new int[128]; for (i=0; n ; i++,n&gt;&gt;=1) digits[i]=(n &amp; 1)? 1:0; first1=i-1; } Binary&amp; operator =(const Binary&amp; b){ if (this==&amp;b) return *this; memcpy(digits,b.digits,128*sizeof(int)); first1=b.first1; return *this; } Binary(int n) { int i; digits = new int[128]; for (i=0; n ; i++,n&gt;&gt;=1) digits[i]=(n &amp; 1)? 1:0; first1=i-1; } void print() { for (int i=first1; i&gt;=0 ; i--) cout&lt;&lt;digits[i]; cout&lt;&lt;endl; } operator int() { int x = 1,sum=0; for (int i=0; i&lt;=first1 ; i++,x&lt;&lt;=1) sum+=digits[i]*x; return sum; } Binary&amp; operator +(Binary&amp; a) { int overflow = 0; Binary* b1=new Binary(); int max = a.first1&gt;this-&gt;first1? a.first1 : this-&gt;first1,bit; for (int i=0; i&lt;=max ; i++) { bit=a.digits[i]+this-&gt;digits[i]+overflow; overflow=0; if (bit&gt;1) overflow=1; b1-&gt;digits[i]=bit%2; } return *b1; } }; </code></pre> <p>and the main using it:</p> <pre><code>int main() { Binary b(91); int x=9; Binary *b2=new Binary(); *b2=b+x; x=*b2; b2-&gt;print(); cout&lt;&lt;" = "&lt;&lt;x; cin&gt;&gt;x; } </code></pre> <p>lets talk about the line:</p> <pre><code>*b2=b+x; </code></pre> <p>first the compiler implicitly allocates a new binary instance for int x, then using it as a paramater for the addition, then creates a new binary instance for the addition result and copies it bit by bit to *b2.</p> <p>The problem is, that if you run this code, it only prints deleting ONCE, while there were 2 objects created for the execution of the command. apparently there's a leak comes from the addition code, in which i explicitly created a new object to return the result.</p> <p><strong>Q1</strong>: am i correct?</p> <p><strong>Q2</strong>: what can i do to overcome this?</p> <p><strong>EDIT</strong>: The answer and more about the topic of operator overloading can be found <a href="https://stackoverflow.com/questions/4421706/operator-overloading">here</a></p>
    singulars
    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.
 

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